如果主窗口右键单击,则会显示
QInputDialog
。我希望 QInputDialog
在主窗口打开时阻止它。如何实现这一目标?
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])
class AppWindow(QtGui.QMainWindow):
def __init__(self):
super(AppWindow, self).__init__()
mainWidget=QtGui.QWidget()
self.setCentralWidget(mainWidget)
mainLayout = QtGui.QVBoxLayout()
mainWidget.setLayout(mainLayout)
frame=QtGui.QFrame()
frame.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
frame.connect(frame, QtCore.SIGNAL("customContextMenuRequested(QPoint)" ), self.up)
mainLayout.addWidget(frame)
self.modal=QtGui.QInputDialog()
def up(self, QPos):
self.modal.move(QtGui.QCursor.pos())
self.modal.show()
self.modal.raise_()
window=AppWindow()
window.show()
sys.exit(app.exec_())
好的,这个解决方案可以通过使用方法
QWidget.setWindowModality (self, Qt.WindowModality windowModality)
来解决。 模态窗口是一种阻止其他窗口输入的窗口。请注意,模态窗口的子窗口不会被阻止。
在您的初始方法中添加此行;
self.modal.setWindowModality(QtCore.Qt.ApplicationModal)
完成的代码是;
import sys
from PyQt4 import QtCore, QtGui
class AppWindow (QtGui.QMainWindow):
def __init__ (self):
super(AppWindow, self).__init__()
mainWidget = QtGui.QWidget(self)
self.setCentralWidget(mainWidget)
mainLayout = QtGui.QVBoxLayout()
mainWidget.setLayout(mainLayout)
frame = QtGui.QFrame()
frame.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
frame.connect(frame, QtCore.SIGNAL("customContextMenuRequested(QPoint)" ), self.up)
mainLayout.addWidget(frame)
self.modal = QtGui.QInputDialog(self)
self.modal.setWindowModality(QtCore.Qt.ApplicationModal)
def up (self, QPos):
self.modal.move(QtGui.QCursor.pos())
self.modal.show()
self.modal.raise_()
app = QtGui.QApplication([])
window = AppWindow()
window.show()
sys.exit(app.exec_())
参考方法:http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#setWindowModality
参考枚举:http://pyqt.sourceforge.net/Docs/PyQt4/qt.html#WindowModality-enum
问候,
简而言之,这是基本方法。我创建了第二个窗口(一个框架),其中包含一个表格小部件,我的类的名称是 TableWindow。将其导入主窗口文件中。单击按钮后,我调用以下函数。
def call_table_window(self):
self.frame = QtGui.QFrame()
self.window_table = TableWindow()
self.window_table.setupUi(self.frame)
#This stops the user to switch to the main window. He has to close
#the 2nd window first.
self.frame.setWindowModality(QtCore.Qt.ApplicationModal)
self.frame.show()
特别是在使用 PyQt5 时,您可以在
__init__
内部设置
self.setWindowModality(QtCore.Qt.ApplicationModal)
对于 PySide6 和 PyQt6:
self.setWindowModality(Qt.WindowModality.ApplicationModal)