【发布时间】:2019-12-30 17:43:39
【问题描述】:
我正在编写一个小型 PyQt 应用程序,它需要在应用程序启动之前运行一些检查,如果任何检查失败,应用程序需要通知用户它无法运行然后退出。
在 WinForms 中。我可以简单地做到这一点:
var form = new Form();
form.Activated += (s, e) =>
{
var condition = true;
if (condition)
{
MessageBox.Show("oh dear, something's wrong.");
Application.Exit();
}
};
当主应用程序窗口加载时,PyQt 似乎没有可以连接的信号,并且当条件失败时我当前的尝试甚至没有触发对话框。
这是我目前拥有的(MRE(。程序流程如下:
import sys
import winreg
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
def loadData(self):
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Path\To\Nonexistant\Key')
x = winreg.QueryValueEx(key, 'some_key')[0]
print(x)
except FileNotFoundError:
error = QMessageBox()
error.setIcon(QMessageBox.Critical)
error.setText('Cannot locate installation directory.')
error.setWindowTitle('Cannot find registry key')
error.setStandardButtons(QMessageBox.Ok)
error.show()
QApplication.quit()
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
main_window.loadData()
sys.exit(app.exec_())
main()
我的最终目标是让loadData() 在应用程序完全加载并显示给用户时运行。
更新:程序现在按预期运行。我不得不:
- 将
error.show()更改为error.exec_() - 将
QApplication.quit()更改为sys.exit() - 在
main_window.show()之后致电main_window.loadData()
【问题讨论】:
-
据我了解(我不知道 winforms),您希望应用程序在用户单击 QMessageBox 上的 OK 后结束,对吗?
-
没错。一旦应用程序加载,我需要它来执行检查,如果它失败,显示 QMessageBox 然后退出。我现在根本无法显示 QMessageBox。