使用show()
或exec_()
显示QDialog后,我需要动态添加一些其他小部件。我怎样才能做到这一点?
最佳答案
只需在您的窗口小部件上调用show()
:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class testDialogs(QWidget):
def __init__(self, parent=None):
super(testDialogs, self).__init__(parent)
self.verticalLayout = QVBoxLayout(self)
self.pushButton = QPushButton(self)
self.pushButton.setText("Open a Dialog")
self.pushButton1 = QPushButton(self)
self.pushButton1.setText("Add a Text Edit")
self.plainTextEdit = QPlainTextEdit(self)
self.plainTextEdit.appendPlainText("This is a Widget")
self.verticalLayout.addWidget(self.pushButton)
self.verticalLayout.addWidget(self.pushButton1)
self.verticalLayout.addWidget(self.plainTextEdit)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.pushButton1.clicked.connect(self.on_pushButton1_clicked)
@pyqtSlot()
def on_pushButton_clicked(self):
dialog = QDialog(self)
verticalLayout = QVBoxLayout(dialog)
plainTextEdit = QPlainTextEdit(dialog)
plainTextEdit.appendPlainText("This is a Dialog")
buttonBox = QDialogButtonBox(dialog)
buttonBox.setOrientation(Qt.Horizontal)
buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
buttonBox.setObjectName("buttonBox")
verticalLayout.addWidget(plainTextEdit)
verticalLayout.addWidget(buttonBox)
buttonBox.accepted.connect(dialog.close)
buttonBox.rejected.connect(dialog.close)
dialog.show()
@pyqtSlot()
def on_pushButton1_clicked(self):
plainTextEdit = QPlainTextEdit(self)
plainTextEdit.appendPlainText("This is another Text Edit")
self.verticalLayout.addWidget(plainTextEdit)
plainTextEdit.show()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = testDialogs()
main.show()
sys.exit(app.exec_())