【问题标题】:QCoreApplication::exec: The event loop is already running - Calling another PyQt5 fileQCoreApplication::exec: 事件循环已经在运行 - 调用另一个 PyQt5 文件
【发布时间】:2020-11-01 03:01:52
【问题描述】:

我正在运行一个带有按钮的 PyQt5 应用程序,它应该在单独的窗口中调用另一个 PyQt5 文件。我将按钮设置为调用另一个 PyQt5 中的“main2”函数,该函数 .show 另一个文件。独立它们工作得很好,但是当我尝试以这种方式连接它们时,我得到了上面的错误。

from ShowRecords import main2

class ExerciseTracker(QDialog):
    def __init__(self):
        super().__init__()
        self.myWindow = QDialog()
        #self.title = 'Exercise Tracker'
        self.myWindow.setWindowTitle('Exercise Tracker')
        self.setGeometry(200, 400, 300, 200)
        self.move(60, 15)
        self.layout = QFormLayout()
        self.layout.addRow(QLabel('<h2>Welcome to the App!</h2>', parent=self.myWindow))
        line_edit1 = QLineEdit()
        self.layout.addRow('Day of the week: ', line_edit1)
        line_edit2 = QLineEdit()
        self.layout.addRow('Body Part: ', line_edit2)
        line_edit3 = QLineEdit()
        self.layout.addRow('Input Exercise: ', line_edit3)
        line_edit4 = QLineEdit()
        self.layout.addRow('Input Sets: ', line_edit4)
        line_edit5 = QLineEdit()
        self.layout.addRow('Input Reps: ', line_edit5)
        btn1 = QPushButton('Submit')
        self.layout.addRow(btn1)
        btn2 = QPushButton('Show Records')
        self.layout.addRow(btn2)
        #btn1.clicked.connect('submit')
        btn2.clicked.connect(main2)
        # layout.addWidget()
        self.myWindow.setLayout(self.layout)
        self.myWindow.show()

def main():
    exercise = QApplication(sys.argv)
    view = ExerciseTracker()
    #view.show()
    sys.exit(exercise.exec_())

if __name__ =='__main__':
    main()

另一个文件叫做 ShowRecord 我叫的是这个'

def main2():
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt5


    【解决方案1】:

    您可以使用以下方式检查事件循环是否已经在运行:

    app = QtCore.QCoreApplication.instance()
    if app is None:
        app = QtWidgets.QApplication(sys.argv)
    

    但是,几乎可以肯定有更好的方式来布置您的 gui。一种可能的方法是创建一个 QWidget 子类来封装 Ui_Form 的行为并导入该类而不是不同的 main() 方法。然后您可以让您的 ExerciseTracker 小部件创建子“Ui_Form”小部件,这将保证所有正确的 Qt 内存管理等都在发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多