【问题标题】:PyQt5 can't use pre defined widgets in separate ui filePyQt5 不能在单独的 ui 文件中使用预定义的小部件
【发布时间】:2017-05-20 11:36:46
【问题描述】:

我在使用 PyQt5 时遇到问题,我有一个单独的 ui 文件(仍然是一个 python 文件而不是 .ui)我正在尝试连接一个位于该文件中的按钮,但这对我不起作用由于某些原因。 这是我的代码。

from PyQt5 import QtCore, QtGui, QtWidgets
from gui import Ui_Form

class Main(QtWidgets.QMainWindow):
    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.show()
        self.Ui_Form.exit.clicked.connect(self.handle)

    def handle(self):
        self.print("hello")

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

这是我使用 pyuic 自动生成的 gui 文件中的一些代码:

self.exit = QtWidgets.QPushButton(Form)
self.exit.setGeometry(QtCore.QRect(375, 270, 115, 27))
self.exit.setObjectName("exit")

这个完全相同的过程在 Qt4 之前对我有用,所以我不明白为什么它在这里不起作用?

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 qt-designer


    【解决方案1】:

    您必须使用 ui 属性来访问按钮。你必须改变:

    self.Ui_Form.exit.clicked.connect(self.handle)
    

    到:

    self.ui.exit.clicked.connect(self.handle)
    

    注意:通常在使用Widget template 时,它将该元素命名为form,将设计类命名为Ui_Form,因此您应该使用QWidget 作为类基。

    完整代码:

    class Main(QtWidgets.QWidget):
        def __init__(self):
            super(Main, self).__init__()
            self.ui = Ui_Form()
            self.ui.setupUi(self)
            self.show()
            self.ui.exit.clicked.connect(self.handle)
    
        def handle(self):
            self.print("hello")
    
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = Main()
        w.show()
        sys.exit(app.exec_())
    

    【讨论】:

    • 是的,我知道它应该是 ui,但它不起作用,所以我有点绝望..
    • @SS2 你基于 Qt Designer 的什么模板:MainWindow、Dialog 或 Widget?
    • 还看得更好,我发现你从不使用Main
    • 哈哈,我只是犯了一个愚蠢的错误,没有运行 Main()。谢谢!
    猜你喜欢
    • 2018-07-09
    • 2021-08-04
    • 2017-11-06
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2022-07-02
    相关资源
    最近更新 更多