我有以下代码(最小可重现的示例):
关闭.py
import sys
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5 import uic
class DialogWindow(QDialog):
def __init__(self):
super().__init__()
uic.loadUi('close.ui', self)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
def accept(self):
print("accept...")
self.close()
def reject(self):
print("reject...")
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = DialogWindow()
main_window.show()
sys.exit(app.exec_())
关闭.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>New Experiment</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>100</x>
<y>250</y>
<width>193</width>
<height>28</height>
</rect>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
尽管事实上,当您单击QDialogButtonBox相应的方法(accept()和reject())时,它们会起作用,但窗口仍然不想关闭。可能是什么问题呢?
UPD:我更改了方法和信号的名称(分别将accept 更改为accept2 并将reject 更改为reject2),一切正常。难道是父类?我将这些方法设为accept()私有reject(),它也有效......
通常您的任务如下所示: