我希望当用户按下按钮时,在主窗口被阻止等待表单填写后会出现一个表单
您不需要执行其他答案建议的任何操作。使用任何
exec()
方法肯定会出现错误,因为突然你的 gui 代码可以重新输入。别这样做。
您需要做的就是在显示之前设置正确的窗口模式(这是重要的部分)。所以:
widget.setWindowModality(Qt.ApplicationModal)
widget.show()
如果您希望窗口仅阻止其他一些窗口,而不是整个应用程序:
widget.setWindowFlags(widget.windowFlags() | Qt.Window)
widget.setParent(otherWindow)
widget.setWindowModality(Qt.WindowModal)
widget.show()
请注意,此代码仅适用于 PyQt4,它不适用于 Qt 5,因为在那里,窗口功能属于与 QWidget 分开的类。
QDialog 并使用 exec 显示它,这将阻止应用程序的其余部分,直到它关闭。 exec
的返回值还告诉您表单是否在未提交更改的情况下关闭(即取消)。这是一个简单的演示脚本,展示了如何使用
QDialog
:
from PyQt5 import QtWidgets, QtCore
# from PyQt6 import QtWidgets, QtCore
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.checkbox1 = QtWidgets.QCheckBox('Option one')
self.checkbox2 = QtWidgets.QCheckBox('Option two')
self.buttonOk = QtWidgets.QPushButton('Ok')
self.buttonOk.clicked.connect(self.accept)
self.buttonCancel = QtWidgets.QPushButton('Cancel')
self.buttonCancel.clicked.connect(self.reject)
layout = QtWidgets.QGridLayout(self)
layout.addWidget(self.checkbox1, 0, 0, 1, 2)
layout.addWidget(self.checkbox2, 1, 0, 1, 2)
layout.addWidget(self.buttonOk, 2, 0)
layout.addWidget(self.buttonCancel, 2, 1)
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
self.button = QtWidgets.QPushButton('Show Dialog')
self.button.clicked.connect(self.handleButton)
layout.addWidget(self.button)
self.setCentralWidget(widget)
def handleButton(self):
dialog = Dialog(self)
if dialog.exec_() == QtWidgets.QDialog.DialogCode.Accepted:
print('Option one:', dialog.checkbox1.isChecked())
print('Option two:', dialog.checkbox2.isChecked())
else:
print('Cancelled')
dialog.deleteLater()
if __name__ == '__main__':
app = QtWidgets.QApplication(['Test'])
window = Window()
window.setGeometry(500, 300, 200, 100)
window.show()
app.exec()
self.setWindowModality(QtCore.Qt.ApplicationModal)
QObject::connect(myPushButton, SIGNAL(clicked), this, SLOT(on_myPushButton()));
//...
void MainWindow::on_myPushButton()
{
Dialog d;
int retVal = d.exec();// this is a blocking call
// Here the user has finished filling out the form.
// save any data that should be in the form, or respond to the retVal
}
编辑:添加了有关使用
QDialog::exec()
的文档链接
http://qt-project.org/doc/qt-5/qdialog.html#exec
希望有帮助。
AjoutArBase, AjoutArForm = uic.loadUiType('ajoutArticle.ui')
class AjoutArticle(AjoutArBase,QtGui.QDialog):