23

Well, I'm writing a small PyQt4 app, it's just a single Yes/No dialog which has to execute an external command (e.g. '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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Laszlo Meller
  • 233
  • 1
  • 2
  • 4

4 Answers4

52
btn.clicked.connect(self.close)

That would be my suggestion

Manjabes
  • 1,884
  • 3
  • 17
  • 34
10

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)
...
Jesse Harris
  • 1,131
  • 6
  • 10
9

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.

Lightsout
  • 3,454
  • 2
  • 36
  • 65
g07kore
  • 290
  • 2
  • 7
1

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_()
user12121533
  • 23
  • 1
  • 6