在没有 MainWindow 的情况下显示 Qwidget window

show Qwidget window without MainWindow

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

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

我用 QtDesigner 创建了 window,现在我正尝试像这样显示 QWidget window:

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

然后,从我的主要 class,我这样做:

class myMainClass():

    childWindow = childInputData()

这给了我错误:

QWidget: Must construct a QApplication before a QPaintDevice

所以现在我正在做,从我的主要 class:

class myMainClass():

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

现在没有错误了,但是 window 显示了两次并且脚本没有等到数据输入,它只显示 window 并且没有等待就继续。

这里有什么问题?

你不需要 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_())

显示 window 并且脚本继续运行是完全正常的:您从未告诉脚本等待用户回答。你刚刚告诉它显示 window.

您希望脚本停止,直到用户完成并且 window 关闭。

这是一种方法:

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()方法"Enters the main event loop and waits until exit() is called"(doc):
脚本将在 app.exec_() 行被阻塞,直到 window 关闭。

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


另一种方法是使用 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,而是将window模态设置为win.setWindowModality(QtCore.Qt.ApplicationModal)。然而,这在这里不起作用:它会阻止其他 windows 中的输入,但不会阻止脚本。