如何在python中关闭QMessageBox及其父对话框

时间:2015-08-18 18:55:08

标签: python-2.7 pyqt qdialog

如何在按下QMessageBox.information按钮时关闭弹出对话框及其ok

我从here

获得了此代码

我在我的模块中使用它作为弹出对话框。该对话框将打开另一个QMessageBox.information及其标准ok按钮

this one http://i60.tinypic.com/28kocih.jpg

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import serial
from serial.serialutil import SerialException
from serialutils import full_port_name, enumerate_serial_ports


class ListPortsDialog(QDialog):
    def __init__(self, parent=None):
        super(ListPortsDialog, self).__init__(parent)
        self.setWindowTitle('List of serial ports')

        self.ports_list = QListWidget()
        self.tryopen_button = QPushButton('Try to open')
        self.connect(self.tryopen_button, SIGNAL('clicked()'),
        self.on_tryopen)

        layout = QVBoxLayout()
        layout.addWidget(self.ports_list)
        layout.addWidget(self.tryopen_button)
        self.setLayout(layout)

        self.fill_ports_list()

   def on_tryopen(self):
        cur_item = self.ports_list.currentItem()
        if cur_item is not None:
            fullname = full_port_name(str(cur_item.text()))
            try:
                ser = serial.Serial(fullname, 38400)
                ser.close()
                QMessageBox.information(self, 'Success',
                    'Opened %s successfully' % cur_item.text())
            except SerialException, e:
                QMessageBox.critical(self, 'Failure',
                    'Failed to open %s:\n%s' % (
                    cur_item.text(), e))

    def fill_ports_list(self):
        for portname in enumerate_serial_ports():
            self.ports_list.addItem(portname)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = ListPortsDialog()
    form.show()
    app.exec_()

我想在按下确定按钮时关闭窗口3和窗口2

1 个答案:

答案 0 :(得分:1)

由于它在QMessageBox.information(self, 'Success', 'Opened %s successfully' % cur_item.text())之后使用QDialog,因此您可以简单地说self.accept()。这应该关闭2和3个窗口。