当parentWidget关闭时,浮动QDockWidget不会关闭

时间:2017-08-20 23:13:15

标签: python python-2.7 pyqt pyqt4

我有两个打开的MainWindows:MainWindowWithButton和MainWindowWithDock。后者包含一个QDockWidget。

IS行为:当用户使DockWidget浮动并关闭MainWindowWithDock时,dockWidget不会关闭。

SHOULD行为:当用户使DockWidget浮动并关闭MainWindowWithDock时,dockWidget也会关闭。

注意:

  • " IS行为的原因":浮动的DockWidget似乎独立于它的父母
  • 我无法听取onClose / reject(因为它会在我的特定情况下提供虚假信息。
  • MainWindow没有发出有关其行为的明确信号
  • 重要的是,DockWidget在关闭MainWindow之前关闭 。否则焦点会出乎意料

示例代码:

from PyQt4 import QtCore, QtGui
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QApplication, QDialog, QMainWindow
import sys

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindowWithButton(object):
    def setupUi(self, MainWindowWithButton):
        MainWindowWithButton.setObjectName(_fromUtf8("MainWindowWithButton"))
        MainWindowWithButton.resize(567, 384)
        self.centralwidget = QtGui.QWidget(MainWindowWithButton)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        MainWindowWithButton.setCentralWidget(self.centralwidget)

    def retranslateUi(self, MainWindowWithButton):
        MainWindowWithButton.setWindowTitle(_translate("MainWindowWithButton", "MainWindow", None))

class Ui_MainWindowWithDock(object):
    def setupUi(self, MainWindowWithDock):
        MainWindowWithDock.setObjectName(_fromUtf8("MainWindowWithDock"))
        MainWindowWithDock.resize(509, 316)
        self.centralwidget = QtGui.QWidget(MainWindowWithDock)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        MainWindowWithDock.setCentralWidget(self.centralwidget)

        # # # # # # # # # # # # # # # # # # # # # #
        # # #     setup dock      # # # # # # # # #
        # # # # # # # # # # # # # # # # # # # # # #
        self.theDock = QtGui.QDockWidget(MainWindowWithDock)
        self.theDock.setObjectName(_fromUtf8("theDock"))
        self.dockWidgetContents = QtGui.QWidget(self.theDock)
        self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents"))
        self.theDock.setWidget(self.dockWidgetContents)
        MainWindowWithDock.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.theDock)

        self.retranslateUi(MainWindowWithDock)
        QtCore.QMetaObject.connectSlotsByName(MainWindowWithDock)

    def retranslateUi(self, MainWindowWithDock):
        MainWindowWithDock.setWindowTitle(_translate("MainWindowWithDock", "MainWindow", None))

class MainWindowWithButtonDlg(QMainWindow):
    pass

class MainWindowWithDockDlg(QMainWindow):
    pass

def main():
    app = QApplication(sys.argv)

    windowWithDockUi = Ui_MainWindowWithDock()
    windowWithDock = MainWindowWithDockDlg()
    windowWithDockUi.setupUi(windowWithDock)
    windowWithDock.show()
    app.exec()

    # the dock widget should be closed by now

    ui = Ui_MainWindowWithButton()
    window = MainWindowWithButtonDlg()
    ui.setupUi(window)
    window.show()
    app.exec()



if __name__ == '__main__':
    main()

拒绝原始来源的方法。在这里,我们有一个带有QMainwindow的QDialog作为它的中央Widget - 因此它在某种意义上变成了QMainWindow(from Anki addCards.py (scroll to bottom)

def reject(self):
    if not self.canClose(): # this way of calling is basically the problem: we might leave this method without doing anything
        return
    remHook('reset', self.onReset)
    remHook('currentModelChanged', self.onModelChange)
    clearAudioQueue()
    self.removeTempNote(self.editor.note)
    self.editor.setNote(None)
    self.modelChooser.cleanup()
    self.deckChooser.cleanup()
    self.mw.maybeReset()
    saveGeom(self, "add")
    aqt.dialogs.close("AddCards")
    QDialog.reject(self)

1 个答案:

答案 0 :(得分:1)

您可以使用event-filter来监控给定窗口的所有事件。在窗口关闭之前,它将始终发布一个关闭事件。窗口是否修改了正常的关闭过程并不重要。如果它最终关闭,则相应的关闭事件的accept property 保证True。因此,如果您观看此活动,您只需检查是否已被接受,然后采取相应行动。

要解决的主要问题是如何找到合适的观看窗口。在创建dock-widget时,可能无法访问它。因此,一种方法是等待直到第一次显示dock-widget的父级,然后查找顶级窗口并在其上安装事件过滤器。以这种方式做事意味着dock-widget永远不需要了解它最终依赖的窗口。

以下是基于您的示例的此方法的工作演示(删除了大部分不相关的内容):

import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QApplication, QDialog, QMainWindow

class EventWatcher(QtCore.QObject):
    def __init__(self, parent):
        QtCore.QObject.__init__(self, parent)
        parent.installEventFilter(self)

    def eventFilter(self, source, event):
        if source is self.parent():
            if event.type() == QtCore.QEvent.Show:
                target = source.parent()
                while target.parent() is not None:
                    target = target.parent()
                print('found target window: %r' % target)
                source.removeEventFilter(self)
                target.installEventFilter(self)
        elif event.type() == QtCore.QEvent.Close:
            source.closeEvent(event)
            print('test filter accepted: %s' % event.isAccepted())
            if event.isAccepted():
                self.parent().close()
            return True
        return QtCore.QObject.eventFilter(self, source, event)

class Ui_MainWindowWithDock(object):
    def setupUi(self, MainWindowWithDock):
        self.theDock = QtGui.QDockWidget(MainWindowWithDock)
        MainWindowWithDock.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.theDock)
        # add the event watcher
        EventWatcher(self.theDock)

class MainWindowWithDockDlg(QMainWindow):
    pass

# mock-up class for testing
class MockDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        windowWithDock = MainWindowWithDockDlg()
        windowWithDockUi = Ui_MainWindowWithDock()
        windowWithDockUi.setupUi(windowWithDock)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(windowWithDock)
        self.canClose = False

    def reject(self):
        if not self.canClose:
            self.canClose = True
            return
        QDialog.reject(self)

    def closeEvent(self, event):
        QDialog.closeEvent(self, event)
        print('test close accepted: %s' % event.isAccepted())

def main():
    app = QApplication(sys.argv)

    dialog = MockDialog()
    dialog.show()
    app.exec_()

    # the dock widget should be closed by now

    window = QMainWindow()
    window.show()
    app.exec_()

if __name__ == '__main__':
    main()