Qt的。了QSplitter。当光标在分割器下时,处理双击

时间:2014-07-01 21:22:29

标签: c++ qt

当光标位于拆分器下时,我需要对QSplitter进行双击。

我重新定义了mouseDoubleClickEvent。但这不适用于这种情况。

当我执行doulble时,当光标位于拆分器下时(准备移动拆分器),方法不会调用。

2 个答案:

答案 0 :(得分:2)

您可以使用事件过滤器过滤转到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); 

     ...
}

答案 1 :(得分:0)

我需要相同的功能,以便在用户双击手柄时能够均匀地分隔分割器中的小部件(这是我的用例)。覆盖QSplitter.mouseDoubleClickEvent()不起作用,因为似乎句柄消耗双击事件本身,因此它不会传播到父QSplitter。在使用eventFilter的已接受答案中提出的解决方案非常好,但缺点是它不是动态的,即当用户向分离器添加新小部件时未安装事件过滤器在运行时。所以我们需要找到一种动态安装事件过滤器的方法。有两种方法可以实现这一目标:

  1. 覆盖QSplitter.addWidget()QSplitter.insertWidget()
  2. # 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

    1. 拦截childEvent(),感觉有点hacky但是有错误证明:
    2. # 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 ++。