testing pyqt application - Qwidget: must construct a qapplication before a qwidget

纵然是瞬间 提交于 2020-01-11 07:26:50

问题


I have a pyqt application and like to test scripts for testing this application.

I was able to build the qapplication during my standalone testing. Not sure how to create this object while writing my unittestcases using 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_())

Unittest:-

    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()

Error:-

QWidget: Must construct a QApplication before a QWidget

回答1:


A QApplication must be created before creating any widget since it handles the eventloop

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()

In the following link there is an example: http://johnnado.com/pyqt-qtest-example/, another option is to use the pytest-qt package



来源:https://stackoverflow.com/questions/51487226/testing-pyqt-application-qwidget-must-construct-a-qapplication-before-a-qwidg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!