以下代码在以下情况下创建一个空对话框 Hello!
摁下。
from PyQt5 import QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
w = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
w.setLayout(layout)
self.setCentralWidget(w)
toyButton = QtWidgets.QPushButton("Hello!")
layout.addWidget(toyButton)
toyButton.clicked.connect(self.showdialog)
def showdialog(self):
d = QtWidgets.QDialog()
d.setWindowTitle("Dialog")
d.setWindowModality(QtCore.Qt.WindowModal)
d.exec_()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()
我怎么能强迫对话框出现 内 主窗口,而不是让它作为一个独立的窗口漂浮着?
你只需要给对话框一个父部件。d = QtWidgets.QDialog(self.centralWidget())
. self
也是一个有效的父部件;选择你最喜欢的部件吧
你也可以添加 d
到布局。self.centralWidget().layout().addWidget(d)
尽管第二种方法不尊重你的模式+执行。
下面是比较两种方法的完整代码。
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
w = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
w.setLayout(layout)
self.setCentralWidget(w)
toyButton = QtWidgets.QPushButton("Hello!")
layout.addWidget(toyButton)
toyButton.clicked.connect(self.showdialog)
toyButton2 = QtWidgets.QPushButton("Hello2!")
layout.addWidget(toyButton2)
toyButton2.clicked.connect(self.showdialog2)
def showdialog(self):
d = QtWidgets.QDialog(self.centralWidget())
d.setWindowTitle("Dialog")
d.setWindowModality(QtCore.Qt.WindowModal)
d.exec_()
def showdialog2(self):
d = QtWidgets.QDialog()
d.setWindowTitle("Dialog2") # window title won't be seen...
d.setWindowModality(QtCore.Qt.WindowModal)
QtWidgets.QPushButton('Dialog2', parent=d) # ... so we add a little something
self.centralWidget().layout().addWidget(d)
d.exec_()