Qt, QSplitter.处理鼠标在拆分器下时的双击

Qt. QSplitter. Handle double click when cursor is under splitter

本文关键字:双击 拆分 QSplitter 处理 鼠标 Qt      更新时间:2023-10-16

我需要处理鼠标在拆分器下双击QSplitter。

我重新定义了mouseDoubleClickEvent。但这在这种情况下不起作用

当我双击光标在拆分器下时(准备移动拆分器),方法没有调用

您可以使用事件过滤器来过滤进入Qsplitter句柄的所有事件:

bool MyClass::eventFilter(QObject * obj, QEvent * event)
{
    if(event->type()==QEvent::MouseButtonDblClick)
    {
        ...
    }
    return false;
}

也不要忘记在你的类的构造函数中安装事件过滤器:

MyClass::MyClass(QWidget *parent):QWidget(parent)
{
     ...
     ui->splitter->handle(1)->installEventFilter(this); 
     ...
}

我也需要这样做,以便在用户双击句柄时能够均匀地分隔分隔器中的小部件(这是我的用例)。重写QSplitter.mouseDoubleClickEvent()不工作,因为似乎句柄消耗双击事件本身,所以它没有传播到父QSplitter。在使用eventFilter的可接受答案中提出的解决方案非常好,但缺点是它不是"动态的",即当用户在运行时向拆分器添加新部件时不安装事件过滤器。因此,我们需要找到一种动态安装事件过滤器的方法。有两个选项可以实现这一点:

  1. 覆盖QSplitter.addWidget()QSplitter.insertWidget():

# inside class MySplitter
def addWidget(self, widget):
    super(MySplitter, self).addWidget(widget)  # call the base class
    self.handle(self.count() - 1).installEventFilter(self)
def insertWidget(self, index, widget):
    super(MySplitter, self).insertWidget(index, widget)  # call the base class
    self.handle(index).installEventFilter(self)

但是,当用户添加小部件时,如果不使用这两个方法,而是将父小部件设置为子小部件,这有点问题,尽管文档不鼓励这样做-参见:http://doc.qt.io/qt-5/qsplitter.html#childEvent

  • 拦截childEvent(),这感觉有点黑客,但是错误证明:

  • # inside class MySplitter
    def childEvent(self, event):
        if event.added():
            # Note that we cannot test isinstance(event.child(), QSplitterHandle) 
            # because at this moment the child is of type QWidget, 
            # it is not fully constructed yet.
            # So we assume (hacky but it works) that the splitter 
            # handle is added always as the second child after 
            # the true child widget.
            if len(self.children()) % 2 == 0:
                event.child().installEventFilter(self)
        super(MySplitter, self).childEvent(event)  # call the base class
    

    我正在使用b),它对我很有效。这样做的好处是,您不需要子类化(但是,为了简单起见,我需要子类化),您可以安装另一个事件过滤器来拦截childEvent,并从外部安装事件过滤器。

    对不起,我的代码是PyQt,但我认为它是足够习惯的,很容易翻译成c++。