3

我正在尝试为几个动态添加到 QMainWindow 的 dockWidgets 捕获 closeEvent。我不清楚如何确定哪个小部件已关闭。这是一个简化的示例:

class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.leftDockWidget = QtGui.QDockWidget('pick tool', self)
        self.leftDockWidget.setWidget( QtGui.QLabel('a dock widget') )
        self.addDockWidget( QtCore.Qt.LeftDockWidgetArea, self.leftDockWidget )
        self.leftDockWidget.closeEvent = self.dockWidgetCloseEvent       
        self.show()

    def dockWidgetCloseEvent(self, event):
        print event
        # how to get sender widget ?    

event.sender() 似乎不存在..有什么想法吗?

谢谢

4

2 回答 2

6

实现您想要的一种方法是使用事件过滤器

from PyQt4 import QtGui, QtCore

class Example(QtGui.QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        self.leftDockWidget = QtGui.QDockWidget('pick tool', self)
        self.leftDockWidget.setWidget(QtGui.QLabel('a dock widget'))
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.leftDockWidget)
        self.leftDockWidget.installEventFilter(self)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.Close and
            isinstance(source, QtGui.QDockWidget)):
            print source.windowTitle()
        return super(Example, self).eventFilter(source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Example()
    window.show()
    sys.exit(app.exec_())
于 2012-09-28T18:10:28.027 回答
2
def dockWidgetCloseEvent(self, event):
    self.sender()
于 2013-01-06T07:10:11.213 回答