Search code examples
qtdouble-clickqplaintextedit

QPlainTextEdit double click event


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

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

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

But, although it works for the QDockWidget I am unable to catch the double click event for the 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 message "Double click" is never shown. Any idea what is wrong with the code?


Solution

    1. QTextEdit inherits a QScrollView and when you double click on the viewport of the QTextEdit, the viewport receives the double click event. You can cross check your current code by double clicking on the edges of the text edit. It will capture the event.

    2. To solve this, add the event filter to the view port in addition to the current event filters you have installed as shown below:

      ui->myPlainTextEdit->viewport()->installEventFilter(this);
      
    3. Next, capture the event using this if statement:

         if ((obj == ui->myPlainTextEdit||obj==ui->myPlainTextEdit->viewport()) &&   
              event->type() == QEvent::MouseButtonDblClick) 
         {
              qDebug() << "Double click"<<obj->objectName();
         }
      
    4. You can capture the click position using QMouseEvent:

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