【发布时间】:2012-09-23 11:46:24
【问题描述】:
我创建了一个自定义 QDialog 类并覆盖了 closeEvent 以隐藏对话框,因为它是另一个小部件的子级。我的对话框只能在其父级关闭时关闭,而不是在它被接受、拒绝或用户单击关闭按钮时关闭。
这一切都很好,但现在我需要打开一个到数据库的连接,并且只有在对话框被销毁时才关闭它,而不仅仅是在它关闭时。
我的代码:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
def Log_Closed():
print "Bye bye"
class My_dlg(QDialog):
def __init__(self, parent=None):
QDialog.__init__( self, parent )
#self.conn = open_connection()
print "Connection Opened"
close_btn = QPushButton("Actually Close")
QVBoxLayout(self).addWidget(close_btn)
close_btn.clicked.connect(self.Actually_Close)
self.destroyed.connect(Log_Closed)
def Actually_Close(self):
print "Actually Close"
self.parent().close()
def closeEvent(self, event):
if event.type() == QEvent.Close:
event.ignore()
self.hide()
print "hidden"
# And I guess I need something like
def destroyEvent(self, event):
#self.conn.close()
print "Connection Closed"
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
main= QMainWindow()
tsd = My_dlg(main)
tsd.show()
sys.exit(app.exec_())
有什么想法吗?
【问题讨论】:
-
如果对话框只应在其父级关闭时关闭,为什么不直接使用父级的
closeEvent来执行必要的清理操作? -
我创建了一个小型 python 应用程序,它加载运行各种对话框的文件并使其保持动态,在其中一个子对话框中定义的所有内容都需要保留在那里。我不想关闭在父级的子级中打开的连接,因为这违背了我的设置目的。不过还是谢谢。