【发布时间】:2019-05-25 10:25:25
【问题描述】:
如果用户与应用程序交互,例如按下按钮,然后用户单击 X 按钮,应用程序继续运行,但窗口关闭。我怎样才能完全终止应用程序。它是使用 PyQt5 构建的。
【问题讨论】:
标签: python pyqt pyqt5 exit qtgui
如果用户与应用程序交互,例如按下按钮,然后用户单击 X 按钮,应用程序继续运行,但窗口关闭。我怎样才能完全终止应用程序。它是使用 PyQt5 构建的。
【问题讨论】:
标签: python pyqt pyqt5 exit qtgui
试试看:
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)
button = QPushButton("Quit")
button.clicked.connect(qApp.quit) # <---
gridLayout = QGridLayout(centralWidget)
gridLayout.addWidget(title, 0, 0)
gridLayout.addWidget(button, 1, 0)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )
【讨论】:
qApp - 指向唯一应用程序对象的全局指针。它等价于 QCoreApplication::instance(),但转换为 QApplication 指针,因此仅在唯一应用程序对象为 QApplication 时有效。 quit () 方法 - 告诉应用程序退出并返回代码 0(成功)。请具体说明您需要做什么?
这是一个简单的“Hello World”示例,我从 Qt 教程中复制而来。它使用sys.exit(...) 退出应用程序。
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtCore import QSize
class HelloWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(640, 480))
self.setWindowTitle("Hello world")
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
gridLayout = QGridLayout(self)
centralWidget.setLayout(gridLayout)
title = QLabel("Hello World from PyQt", self)
title.setAlignment(QtCore.Qt.AlignCenter)
gridLayout.addWidget(title, 0, 0)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )
【讨论】: