gpt4 book ai didi

python - 退出/退出 PyQt 程序的正确方法

转载 作者:太空狗 更新时间:2023-10-29 20:12:12 39 4
gpt4 key购买 nike

我有一个带有登录屏幕的脚本,如果按下取消按钮,我想完全退出该应用程序。我尝试了 3 种方法:

  1. 系统退出()
  2. QApplication.quit()
  3. QCoreApplication.instance().quit()

只有数字 1 有效。另外两个使对话框变白,然后闪烁然后挂起,我什至无法切换到其他应用程序。我的代码如下:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *
from PyQt5.QtWidgets import *


import csv
import sys
from datetime import datetime, timedelta, time
import os

from ci_co_table import *
from login import *

class Ci_Co(QMainWindow):
"""Check in and check out module"""

def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)

class Login(QDialog):
"""User login """
def __init__(self):
QDialog.__init__(self)
self.ui = Ui_login_form()
self.ui.setupUi(self)
self.ui.buttonBox.accepted.connect(lambda: self.handle_login(servers=servers))
servers = {}
with open('servers.csv', newline='') as csvfile:
server_reader = csv.reader(csvfile)
for row in server_reader:
self.ui.cbo_db_name.addItem(row[1])
servers[row[1]] = (row[0],row[2])

def handle_login(self, servers=''):
global user
global pword
global database
global server
global bg_colour
user = self.ui.username.text()
pword = self.ui.password.text()
database = self.ui.cbo_db_name.currentText()
server = servers[database][0]
bg_colour = servers[database][1]


if __name__=="__main__":
app=QApplication(sys.argv)
global hotdate
global hotdate_string
global folio_num
global user
global pword
global dbase
global server
pword = ""
global database
global bg_colour
#Login
while True:
if Login().exec_() == QDialog.Accepted:
db = QSqlDatabase.addDatabase("QPSQL");
db.setHostName(server)
db.setDatabaseName(database);
db.setUserName(user);
db.setPassword(pword)
if (db.open()==False):
QMessageBox.critical(None, "Database Error", db.lastError().text())
else:
break
else:
#QApplication.quit()
QCoreApplication.instance().quit()
#sys.exit()


myapp = Ci_Co()
myapp.show()
sys.exit(app.exec_())

最佳答案

调用QCoreApplication.quit()与调用QCoreApplication.exit(0)是一样的。引用自qt docs :

After this function has been called, the application leaves the main event loop and returns from the call to exec(). The exec() function returns returnCode. If the event loop is not running, this function does nothing. [emphasis added]

所以 quit()exit()sys.exit() 完全不同。后者将终止程序,但前者只会终止事件循环(如果它正在运行)。

当用户取消登录对话框时,您的示例应该只调用 sys.exit() 来终止程序。否则,您的程序将陷入阻塞的 while 循环。

关于python - 退出/退出 PyQt 程序的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283705/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com