Cadel Watson
Cadel Watson

Reputation: 43

Make QPushButton close all open program windows

I'm trying to follow this tutorial, however it's made for PyQt4 whilst I'm using PyQt5.

I have a QPushButton object called btn and want its clicked() signal to trigger the QApplication closeAllWindows() slot. I've read the documentation but it doesn't seem to help, I'm new to Python.

Does anybody know how to do this?

Upvotes: 4

Views: 4199

Answers (1)

user1006989
user1006989

Reputation:

Checkout this example:

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

#---------
# IMPORT
#---------
import sys

from PyQt4 import QtGui, QtCore

#---------
# DEFINE
#---------
class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonClose = QtGui.QPushButton(self)
        self.pushButtonClose.setText("Close Windows!")
        self.pushButtonClose.clicked.connect(self.on_pushButtonClose_clicked)

        self.pushButtonWindows = QtGui.QPushButton(self)
        self.pushButtonWindows.setText("Create Windows!")
        self.pushButtonWindows.clicked.connect(self.on_pushButtonWindows_clicked)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButtonClose)
        self.layoutVertical.addWidget(self.pushButtonWindows)

    @QtCore.pyqtSlot()
    def on_pushButtonWindows_clicked(self):
        position = self.rect().bottom()

        for dialogNumber in range(3):
            dialog = QtGui.QDialog(self)
            dialog.show()
            dialog.setGeometry(
                position,
                position,
                dialog.width(),
                dialog.height()
            )

            position += 10

    @QtCore.pyqtSlot()
    def on_pushButtonClose_clicked(self):
        app = QtGui.QApplication.instance()
        app.closeAllWindows()

#---------
# MAIN
#---------
if __name__ == "__main__":    
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.setGeometry(0, 0, 333, 111)
    main.setWindowFlags(
        main.windowFlags() |
        QtCore.Qt.WindowStaysOnTopHint |
        QtCore.Qt.X11BypassWindowManagerHint
    )
    main.show()

    sys.exit(app.exec_())

Upvotes: 1

Related Questions