1

在使用任何一个显示 QDialog 之后,show()或者exec_()我需要动态添加一些额外的小部件。我怎样才能做到这一点?

4

1 回答 1

1

只需调用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_())
于 2012-12-24T02:00:25.943 回答