简体   繁体   中英

PyQt dialog - How to make it quit after pressing a button?

Well, I'm writing a small PyQt4 app, it's just a single Yes/No dialog which has to execute an external command (eg 'eject /dev/sr0') and quit.

The app runs, it executes the command after pressing the "Yes" button, but I cannot make the dialog itself exit when executing the command.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import subprocess
from PyQt4 import QtGui
from PyQt4 import QtCore
from subprocess import call
cmd = 'eject /dev/sr0'

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        btn = QtGui.QPushButton('Yes', self)     
        btn.clicked.connect(lambda: os.system(cmd))
        btn.resize(180, 40)
        btn.move(20, 35)       

        qbtn = QtGui.QPushButton('No', self)
        qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.resize(180, 40)
        qbtn.move(20, 80) 

        self.setWindowTitle('Test')    
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Here is my code. When I click "Yes", it calls the 'eject /dev/sr0' command properly, but after that the dialog is still visible. I have to click "No" to close the app I would like it to close automatically when the command is executed. What should I add/modify?

btn.clicked.connect(self.close)

那将是我的建议

Replace lambda: os.system(cmd) with a function/method that has multiple statements.

def buttonClicked(self):
    os.system(cmd)
    QtCore.QCoreApplication.instance().quit()

...
    btn = QtGui.QPushButton('Yes', self)     
    btn.clicked.connect(self.buttonClicked)
...

Step1: in the Main Class needs to be build a "connection":

self.ui.closeButton.clicked.connect(self.closeIt)

Step2: Creating a function like to close:

def closeIt(self): 
        self.close()

I named to "closeIt" on purpose because if you name it "close" a conflict will occur.

This solution has the advantage if the created GUI is a plugin for another program (like in my case QGIS), only the active GUI will be closed and not the whole program.

Subclass QDialog() and then close it using your object.

class Dialog(QDialog):
    """
        Subclassing QDialog class.
    """
    def __init__(self):
        QDialog.__init__(self)

    def close_clicked(self):
        self.close()

In your main function write following code

dialogbox = Dialog()  # we subclasses QDialog into Dialog
b1= QPushButton("Close",dialogbox)
b1.clicked.connect(dialogbox.close_clicked)
dialogbox.exec_()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM