python - 无法从 PyQt Designer 的代码构建 GUI

标签 python pyqt pyqt5 qt-designer

我从 pyqt designer 制作了一个 GUI 文件,我将其转换为 .py 文件。但是当我在我的 IDE(Pycharm 和 sublime text)中加载该 .py 代码时,我尝试运行它,它运行时没有错误,但是没有加载 GUI 的物理方面,我尝试了来自互联网的自定义代码,效果很好,当我运行该代码时,GUI 出现了。我将提供比我目前正在处理的代码更简单的代码,因为从 pyqt 设计器生成的所有代码似乎在其物理方面对我来说根本不起作用。

from PyQt5 import QtCore, QtGui, QtWidgets

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(170, 200, 91, 30))
        self.pushButton.setObjectName("pushButton")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(30, 40, 113, 30))
        self.lineEdit.setObjectName("lineEdit")

        self.retranslateUi(Form)
        self.pushButton.clicked.connect(self.lineEdit.clear)
        QtCore.QMetaObject.connectSlotsByName(Form)

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

最佳答案

你有两个选择:

1.假设您使用了以下命令:

pyuic5 your_filename.ui -o your_filename.py
# or 
# pyuic5 your_filename.ui > your_filename.py

该命令不会生成窗口对象或调用 show 方法,因此不会显示窗口,您必须使用选项 -x:

pyuic5 your_filename.ui -o your_filename.py -x

2. 添加调用对象的代码:

from PyQt5 import QtCore, QtGui, QtWidgets

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(170, 200, 91, 30))
        self.pushButton.setObjectName("pushButton")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(30, 40, 113, 30))
        self.lineEdit.setObjectName("lineEdit")

        self.retranslateUi(Form)
        self.pushButton.clicked.connect(self.lineEdit.clear)
        QtCore.QMetaObject.connectSlotsByName(Form)

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

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(w)
    w.show()
    sys.exit(app.exec_())

关于python - 无法从 PyQt Designer 的代码构建 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56202939/

相关文章:

python - 在哪里可以找到与 hyperopt 最佳配置对应的损失?

python - len(sys.argv) <= 0 怎么可能?

PyQt:QTreeView 和 QAbstractItemModel 的人类语言

python - PyQt5 在 pyuic 生成的代码之外添加 eventFilter

python - 形状摘要图上的颜色图栏未正确显示

Python:类型错误:文本必须是 unicode 或字节

python - PyQt:当自定义 QAbstractListModel 数据更改时如何更改 QComboBox 中的 currentIndex

python - PyQt:如何在不知道项目索引号的情况下设置组合框当前项目

python - Pyqt5 Qgraphicsview 在负载上适当缩放

python - 如何从 pyqt5 groupbox 发出可以动态更新的信号