PyQt5-在主窗口小部件外部调用函数

时间:2019-12-19 03:50:38

标签: python qt widget pyqt5 qt-designer

我有两个脚本文件,分别是 test_qt.py test.py 。我想在按下按钮时调用一个函数。但是此函数不在Widget文件(test_qt)内。我可以轻松地调用该函数(如果它位于Widget文件中),但是如果我尝试从test_qt中调用它,则会收到此错误“ AttributeError:'Ui_Form'对象没有属性'test_something'” 。我已经检查了许多示例,但尚未解决。我想调用 test_something()函数。我不知道哪里出了错。我定义了 print_something()函数来调用 test_something()

#----test_qt.py----
from PyQt5 import QtCore, QtGui, QtWidgets
from test import*

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(150, 100, 93, 28))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.print_something)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))

    def print_something(self):
        #strong textprint("click")
        self.test_something()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
---------------------------
#---- test.py -------------
def test_something():
    print("clicked")
---------------------------

1 个答案:

答案 0 :(得分:1)

self中删除self.test_something()应该调用导入的函数。

注意:星号导入被视为代码异味,可能污染名称空间,甚至覆盖现有符号。您应该尽量避免它们:)