Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Problem overriding mousePressEvent



  • Hi to everyone,
    I've a custom widget derived from QLineEdit and I'm trying to overload the mousePressEvent to show a popup menu if I press the mouse right button. So far my code is the following:

    void TaskPreview::mousePressEvent(QMouseEvent *event) {
      if (event->button() == Qt::MouseButton::RightButton) {
        _actions->addAction(_moveLeft);
        _actions->addAction(_moveRight);
        _actions->addAction(_delete);
        _actions->popup(QWidget::mapToGlobal(event->pos()));
      }
    }
    

    The menu is correctly rendered, the problem is that on top of it there's another menu and I don't exactly know where it comes from, probably from the original QLineEdit mousePressEvent but I don't know how this is possible, the widget is stored as TaskPreview and has TaskPreview dynamic type.


  • Lifetime Qt Champion

    Hi
    I guess it is the normal context menu.
    To replace it, you should use
    setContextMenuPolicy(Qt::CustomContextMenu);
    and then use the signal that is sent when its time to show it

    connect(thewidget, SIGNAL(customContextMenuRequested(QPoint)),
    SLOT(customMenuRequested(QPoint)));
    and not via mousePressEvent overide

    https://doc.qt.io/qt-5/qwidget.html#customContextMenuRequested



  • @mrjj Thank you for replying, but now I'm wondering where I should define the menu/make it point to a QMenu*. According to what you replied, is it correct to emit the signal customContextMenuRequested(QPoint) in the overrided mousePressEvent, transforming my code as follows?

    void TaskPreview::mousePressEvent(QMouseEvent *event) {
      if (event->button() == Qt::MouseButton::RightButton) {
        emit customMenuRequested(event->pos();
      }
    }
    

  • Lifetime Qt Champion

    @Daniel_Contro
    Hi
    Qt will emit the signal. you just need to set to custom menu and hook up to a slot.
    Then Qt should send you the signal when you right click. you should not have override mousePress event as
    then it wont work unless you call base class also.



  • @mrjj Thanks a lot for the help, it worked. I have another problem with the main window menuBar, may I ask you here or should I open a new thread?


  • Lifetime Qt Champion

    @Daniel_Contro
    hi
    Good to hear.
    best to set this as solved and make a new one as then its easier for others to search :)