QPlainTextEdit double click event

I need to capture a double click event on a QPlainTextEdit that is inside a QDockWidget.

In my actual code, I have set an event filter on the QDockWidget to handle resize operations and on the QPlainTextEdit to handle double click events:

// Resize eventfilter
this->installEventFilter(this);
ui->myPlainTextEdit->installEventFilter(this);

      

But, while it works for QDockWidget, I cannot catch the double click event for QPlainTextEdit:

bool MyDockWidget::eventFilter(QObject *obj, QEvent *event) {
  if (event->type() == QEvent::Resize && obj == this) {
      QResizeEvent *resizeEvent = static_cast<QResizeEvent*>(event);
      qDebug("Dock Resized (New Size) - Width: %d Height: %d",
             resizeEvent->size().width(),
             resizeEvent->size().height());

  } else if (obj == ui->myPlainTextEdit && event->type() == QMouseEvent::MouseButtonDblClick) {
      qDebug() << "Double click";
  }
  return QWidget::eventFilter(obj, event);
}

      

With this code, the Double Click message is never displayed. Any idea what is wrong with the code?

+3


source to share


1 answer


  • QTextEdit

    inherits QScrollView

    , and when double-clicking on the QTextEdit viewport, the viewport receives the double-click event. You can cross-check your current code by double clicking on the edges of the text. It will capture the event.

  • To solve this problem, add an event filter to the view port in addition to the current events filters you have installed, as shown below:

    ui->myPlainTextEdit->viewport()->installEventFilter(this);
    
          

  • Then write the event using this if statement:

       if ((obj == ui->myPlainTextEdit||obj==ui->myPlainTextEdit->viewport()) &&   
            event->type() == QEvent::MouseButtonDblClick) 
       {
            qDebug() << "Double click"<<obj->objectName();
       }
    
          

  • You can fix the position of the click using QMouseEvent

    :

    QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
    qDebug()<<QString("Click location: (%1,%2)").arg(mouseEvent->x()).arg(mouseEvent->y());
    
          



+6


source







All Articles