显示没有主风的Qwidget窗口

2024-09-28 23:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在显示QWidget窗口以供用户输入一些数据时遇到问题。在

我的脚本没有GUI,但我只想显示这个小的QWidget窗口。在

我用QtDesigner创建了这个窗口,现在我试着像这样显示QWidget窗口:

from PyQt4 import QtGui
from input_data_window import Ui_Form

class childInputData(QtGui.QWidget ):

    def __init__(self, parent=None):
        super(childInputData, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setFocus(True)
        self.show()

然后,在我的主课上,我是这样做的:

^{pr2}$

这给了我一个错误:

^{3}$

所以现在我在主修课上:

class myMainClass():

    app = QtGui.QApplication(sys.argv)
    childWindow = childInputData() 

现在没有错误了,但是窗口显示了两次,脚本不会等到数据输入后才显示,它只显示窗口并继续而不等待。在

这里怎么了?在


Tags: 数据用户fromimportselfform脚本ui
2条回答

窗口显示并且脚本继续运行是非常正常的:您从未告诉脚本等待用户回答。你刚刚告诉它要给我一扇窗。在

您希望脚本停止,直到用户完成操作并关闭窗口。在

有一种方法可以做到:

from PyQt4 import QtGui,QtCore
import sys

class childInputData(QtGui.QWidget):

    def __init__(self, parent=None):
        super(childInputData, self).__init__()
        self.show()

class mainClass():

    def __init__(self):
        app=QtGui.QApplication(sys.argv)
        win=childInputData()
        print("this will print even if the window is not closed")
        app.exec_()
        print("this will be print after the window is closed")

if __name__ == "__main__":
    m=mainClass()

exec()方法“进入主事件循环并等待直到exit()被调用”(doc):
脚本将在app.exec_()行被阻止,直到窗口关闭。在

注意:使用sys.exit(app.exec_())将导致窗口关闭时脚本结束。在


另一种方法是使用QDialog,而不是QWidget。然后将self.show()替换为self.exec(),这将阻止脚本

doc

int QDialog::exec()

Shows the dialog as a modal dialog, blocking until the user closes it


最后,一个相关问题的this answer主张不要使用exec,而是用win.setWindowModality(QtCore.Qt.ApplicationModal)设置窗口形式。但是这在这里不起作用:它阻止其他窗口中的输入,但不阻止脚本。在

您不需要myMainClass…请执行以下操作:

import sys
from PyQt4 import QtGui
from input_data_window import Ui_Form

class childInputData(QtGui.QWidget):
  def __init__(self, parent=None):
    super(childInputData, self).__init__(parent)
    self.ui = Ui_Form()
    self.ui.setupUi(self)
    self.setFocus(True)

if __name__ == "__main__":
 app = QtGui.QApplication(sys.argv)
 win = childInputData()
 win.show()
 sys.exit(app.exec_())

相关问题 更多 >