2017-02-25 57 views
0

几周以来,我一直在为一些众所周知的GIS免费软件(QGIS)编写一个插件。我遇到了一些小问题。PyQt4 |处理'X' - 在QDialog中退出按钮

我的插件机制是这样的:

....... 
class DisplayedWindow(object): 

     def __init__(self): 
      #JANEK Main dialog 
      self.window_plugin = QtGui.QDialog() 
      self.window_plugin.setWindowModality(QtCore.Qt.WindowModal) 
      self.window_plugin.setGeometry(150, 150, 750, 675) 
      self.window_plugin.setWindowTitle('the plugin') 
      self.window_plugin.setWindowFlags(Qt.WindowMinimizeButtonHint|Qt.WindowMaximizeButtonHint) 

      ............. (GUI, functions, etc.)....... 

def run(self): 

    dis_win = self.DisplayedWindow() 
    if dis_win.window_plugin.exec_(): 
     pass 

我知道这是不是建立理所应当的,但我是初学者。没问题的是,这个插件工作的非常好,而且我在编写它的过程中已经走得太远,无法改变程序的整个结构。

我正在寻找的(到目前为止找不到的)是一种处理X-exit红色按钮的方法,因此如果用户不想保存,可能会在关闭窗口之前询问用户变化等

我需要这样的东西self.X_close_button.clicked.connect(lambda: closing_stuff())

有谁知道如何接受呢?或者在这样的对话框中以任何其他方式来控制某人关闭窗口(self.window_plugin)后会发生什么?

祝您有个美好的一天!

回答

0

我为你做了一个简单的例子。还有就是整个代码:

import sys 
from PyQt4 import QtGui,QtCore 
from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
class Create_Dialog_Box(QDialog): 
    def __init__(self,parent = None): 
     super(Create_Dialog_Box, self).__init__(parent) 
     self.setGeometry(100,100,500,200) 
    def closeEvent(self,event): 
     quit_msg = "Are you sure you want to exit the dialog?" 
     reply = QtGui.QMessageBox.question(self, 'Message', 
         quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) 
     if reply == QtGui.QMessageBox.Yes: 
      event.accept() 
     else: 
      event.ignore() 

app = QtGui.QApplication(sys.argv) 
w = QtGui.QWidget() 
w.setGeometry(100,100,200,50) 

d = Create_Dialog_Box(w) 

b = QtGui.QPushButton(w) 
b.setText("Click Me!") 
b.move(50,20) 
b.clicked.connect(d.show) 


w.setWindowTitle("PyQt") 
w.show() 
print("End") 
sys.exit(app.exec_()) 

当您尝试退出它提示如图所示如下图的对话框:

enter image description here

希望它帮助。

1

扩展QDialog并覆盖其closeEvent()方法:

class GISDialog(QDialog): 
    def __init__(self, parent=None): 
     super(GISDialog, self).__init__(parent) 

     self.setGeometry(150,150,750,750) 
     self.window_plugin.setWindowTitle('the plugin') 
     # other intitialization 

    def closeEvent(self, event): 
     reply = QMessageBox.question(self, 'Message', 
      "Do you want to save?", QMessageBox.Yes, QMessageBox.No) 

     if reply == QMessageBox.Yes: 
      event.accept() 
     else: 
      event.ignore() 

然后,当你准备使用它:

dialog = GISDialog() 
if dialog.exec(): 
    pass # do stuff on success 
+0

非常感谢,但我仍然有一个问题。主窗口是一个对象,而不是一个类。我怎样才能“替换”这个closeEvent()方法呢? 我试过类似的, self.window_plugin.closeEvent()= closeEvent() 但它会导致错误 – Janek

+0

我在答案中添加了更多信息。 – Crispin

+0

如果'QDialog'是'QMainWindow'的子类呢?我如何说我想重写'QDialog'的'closeEvent'方法而不是'QMainWindow'。 – Blinxen