简体   繁体   中英

PyQt5 Terminate the app without hitting any button or clicking on anything

import sys
from PyQt5.QtWidgets import (QMainWindow, QLabel, QGridLayout, qApp,
                             QApplication, QWidget, QPushButton)
from PyQt5.QtCore import QSize, Qt   

class HelloWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Hello world") 

        centralWidget = QWidget()          
        self.setCentralWidget(centralWidget)   

        title = QLabel("Hello World from PyQt") 
        title.setAlignment(Qt.AlignCenter) # <---

        gridLayout = QGridLayout(centralWidget)          
        gridLayout.addWidget(title,  0, 0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    mainWin.close()
    app.quit()
    sys.exit( app.exec_() )

I want the app to be closed "automatically" (without hitting any button or clicking the "x"). I tried close() and app.quit() however it just closes the window. The app is still running on. Can you, please, help me to overcome this problem?

I think I found a solution. Modifying the cod like this gives the desired answer



import sys
from PyQt5.QtWidgets import (QMainWindow, QLabel, QGridLayout, qApp,
                             QApplication, QWidget, QPushButton)
from PyQt5.QtCore import QSize, Qt   

class HelloWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Hello world") 

        centralWidget = QWidget()          
        self.setCentralWidget(centralWidget)   

        title = QLabel("Hello World from PyQt") 
        title.setAlignment(Qt.AlignCenter) # <---

        gridLayout = QGridLayout(centralWidget)          
        gridLayout.addWidget(title,  0, 0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    timer = QTimer()
    timer.timeout.connect(lambda: app.quit())
    timer.start(100)
    sys.exit( app.exec_() )

The problem here is that we don't have any Python events set up yet. So our event loop never churns the Python interpreter and so our signal delivered to the Python process is never processed. Therefore, our Python process never sees the signal until we hit the exit button of our Qt application window. (source: https://machinekoder.com/how-to-not-shoot-yourself-in-the-foot-using-python-qt/ )

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