[英]PyQt self.close() in __init__()
我在 Python 2.7 下使用 PyQt4 時遇到了一些小問題
我正在寫一個小項目,其中有一些 QDialogs 相互打開。 所以我打開一個對話框並立即打開另一個對話框來檢查某些東西,當有錯誤檢查時,我希望整個對話框關閉。 它看起來像這樣:
class MyDialog(QtGui.QDialog):
def __init__(self):
## should get me a 10 digit number input
text, ok = QtGui.QInputDialog.getText(self, u'Enter check')
if ok:
## if clicked ok, assign tID
tID = text
else:
## else close
self.close()
try:
## checker is a plausibilty check for the input
## checks, if tID is a number and 10 digits long
## and throws an IntegrityWarning if one of these conditions
## is not met
tID = self.checker.checkID(tID)
except IntegrityWarning as e:
## on exception show error dialog
errDialog = QtGui.QMessageBox()
errDialog.setWindowTitle(u'Fehler')
errDialog.setText(e.getWarning())
ok = errDialog.exec_()
if ok != True:
## close the whole dialog if user cancels
self.close()
self.tAccount = self.tControl.getAccount(tID)
所以這基本上就是我所做的,它工作得很好,只是我在分配之前收到了使用 tID 的錯誤消息。 我的程序在那之后工作得很好,但我想知道錯誤來自哪里。 但令我感到好奇的是,即使我將 tAccount 的最后一個賦值放入 try-except: pass 語句中,錯誤也會被拋出到控制台,而不是通過,這應該是顯而易見的。 所以我的猜測是我不能簡單地終止__init__()
例程中的程序。 我嘗試了 return 語句而不是 close() 語句並破壞了 MainWindow 中調用函數中的 QDialog 。 這使得 Dialog 出現並保持空白,因為它是模態的,我不得不關閉它才能在 MainWindow 中恢復。
有人能告訴我為什么 Dialog __init__()
在關閉后恢復嗎?
這是 Python 的正常行為。 self.close()
不是 return 語句,因此它不會從__init__
退出。
此外, __init__
實際上並沒有在屏幕上顯示對話框,因此在__init__
編寫self.close()
是沒有意義的。 我建議重構您的代碼,以便此應用程序邏輯在__init__
之外,並將根據QInputDialog
和checker
的結果決定是否初始化和顯示MyDialog
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.