pas*_*053 4 python pyqt pyside
嗨,大家好.
我正在使用Windows 7中的python3.4,PyQt5制作GUI应用程序.
申请很有样.用户单击主窗口的按钮,弹出信息对话框.当用户单击信息对话框的关闭按钮(窗口的X按钮)时,系统会显示确认消息.这是所有的了.
这是我的代码.
# coding: utf-8
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QLabel
class mainClass(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
openDlgBtn = QPushButton("openDlg", self)
openDlgBtn.clicked.connect(self.openChildDialog)
openDlgBtn.move(50, 50)
self.setGeometry(100, 100, 200, 200)
self.show()
def openChildDialog(self):
childDlg = QDialog(self)
childDlgLabel = QLabel("Child dialog", childDlg)
childDlg.resize(100, 100)
childDlg.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
mc = mainClass()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
结果截图是......
在这种情况下,我在mainClass类中添加了这些代码.
def closeEvent(self, event):
print("X is clicked")
Run Code Online (Sandbox Code Playgroud)
此代码仅在主窗口关闭时有效.但是我想要的是closeEvent函数在关闭childDlg时有效.不是主窗口.
我该怎么办?
小智 8
你已经添加了类mainClass中的方法closeEvent.所以你已经重新实现了QMainwindow的方法closeEvent而不是你的childDlg的closeEvent方法.要做到这一点,你必须像这样继承你的chilDlg:
# coding: utf-8
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QLabel
class ChildDlg(QDialog):
def closeEvent(self, event):
print("X is clicked")
class mainClass(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
openDlgBtn = QPushButton("openDlg", self)
openDlgBtn.clicked.connect(self.openChildDialog)
openDlgBtn.move(50, 50)
self.setGeometry(100, 100, 200, 200)
self.show()
def openChildDialog(self):
childDlg = ChildDlg(self)
childDlgLabel = QLabel("Child dialog", childDlg)
childDlg.resize(100, 100)
childDlg.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
mc = mainClass()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)