测试pyqt应用程序-Qwidget:必须在qwidget之前构造一个qapplication

时间:2018-07-23 21:04:27

标签: 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

1 个答案:

答案 0 :(得分:1)

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