python - 测试 pyqt 应用程序 - Qwidget : must construct a qapplication before a qwidget

标签 python pyqt pyqt5 pytest

我有一个 pyqt 应用程序,并且喜欢测试用于测试此应用程序的脚本。

我能够在独立测试期间构建 qapplication。不确定如何在使用 pytest 编写我的单元测试用例时创建此对象。

import sys

from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout, QLabel, QLineEdit


class Example(QDialog):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)            
        self.initUI()

    def initUI(self):
        grid = QGridLayout(self)
        a1 = QLabel('alphanumeric characters')
        a2 = QLabel('alphanumeric characters')

        grid.addWidget(QLabel('Name'), 0, 0)
        grid.addWidget(QLineEdit(), 0, 1)
        grid.addWidget(QLabel('Street1'), 1, 0)
        grid.addWidget(QLineEdit(), 1, 1)
        grid.addWidget(QLabel('Street2'), 2, 0)
        grid.addWidget(QLineEdit(), 2, 1)
        grid.addWidget(QLabel('City'), 3, 0)
        grid.addWidget(QLineEdit(), 3, 1)

        grid.addWidget(QLabel('only alphanumeric'), 0, 2, 4, 1)

        self.setGeometry(500, 500, 500, 500)
        self.setWindowTitle('Lines')
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
#     ex.show()
    sys.exit(app.exec_())

单元测试:-

    import unittest
import same_label


class Test(unittest.TestCase):


    def setUp(self):
        ex = same_label.Example()


    def tearDown(self):
        pass


    def testName(self):
        pass


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

错误:-

QWidget: Must construct a QApplication before a QWidget

最佳答案

在创建任何小部件之前必须创建 QApplication,因为它处理事件循环

import unittest
import same_label
import sys

from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)


class Test(unittest.TestCase):
    def setUp(self):
        ex = same_label.Example()

    def tearDown(self):
        pass

    def testName(self):
        pass


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

以下链接中有一个示例:http://johnnado.com/pyqt-qtest-example/ ,另一个选择是使用 pytest-qt

关于python - 测试 pyqt 应用程序 - Qwidget : must construct a qapplication before a qwidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487226/

相关文章:

python - 为什么我不能将 x 和 y 标签设置为 pd.plot() 的参数,而我可以轻松设置类似的东西,例如标题?

python - 如何将 tsv 文件加载到 Pandas DataFrame 中?

python - How to Pack with PyQt - 如何让QFrame/Layout适应内容

javascript - PyQt5 QWebView : Load . 加载.js文件的html文件

python - PyQt5:如何为每个角色设置自定义鼠标指针?

python - Jupyter 笔记本不断重新连接到内核

python - 将元组的 Rust 向量转换为 C 兼容结构

qlabel 中的 python 错误 : can not show . gif

python - 与 pyQt 一起使用时箱线图不显示

python - 定时器无法连接到pyqt5中的插槽