将 Qt Designer 5.8 与 PyQt5 结合使用:PyQt v3 中的问题示例

Using Qt Designer 5.8 with PyQt5: problematic example from PyQt v3

我了解(或多或少)official documentation除了最后一个例子的页面内容,它是基本上如下(我不关心按钮):

from ui_imagedialog import ImageDialog

class MyImageDialog(ImageDialog):
    def __init__(self):
      super(MyImageDialog, self).__init__()

    # Connect up the buttons.
      self.okButton.clicked.connect(self.accept)

问题:我在尝试了解如何使此代码段起作用时遇到了一些困难。它会引发错误:'cannon import name ImageDialog'。

我应该从上述文档页面的第一个示例中添加什么来使此代码显示对话框 window?

我试过的: 我已经根据需要生成了带有名称 ui_imagedialog.py 的 Python 代码的文件。它具有以下内容,显然可以单独使用:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_ImageDialog(object):
    def setupUi(self, ImageDialog):
        ImageDialog.setObjectName("ImageDialog")
        ImageDialog.resize(303, 204)
        self.pushButton = QtWidgets.QPushButton(ImageDialog)
        self.pushButton.setGeometry(QtCore.QRect(200, 160, 75, 23))
        self.pushButton.setObjectName("pushButton")

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

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


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ImageDialog = QtWidgets.QDialog()
    ui = Ui_ImageDialog()
    ui.setupUi(ImageDialog)
    ImageDialog.show()
    sys.exit(app.exec_())

感谢任何建设性的帮助。

Qt Designer用于创建图形部分,而不是逻辑部分,您必须根据设计中使用的小部件创建逻辑部分。在你的情况下,我认为它是 QDialog.

from ui_imagedialog import Ui_ImageDialog

from PyQt5 import QtCore, QtGui, QtWidgets

class ImageDialog(QtWidgets.QDialog, Ui_ImageDialog):
    def __init__(self, parent=None):
      super(ImageDialog, self).__init__(parent=parent)
      self.setupUi(self)

      self.pushButton.clicked.connect(self.accept)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = ImageDialog()
    w.show()
    sys.exit(app.exec_())

观察:ui_imagedialog.py文件中没有ImageDialogclass,只有Ui_ImageDialogclass,所以我产生了错误。同样在设计中,按钮被称为 self.pushButton, 所以你不能称它为 self.okButton.