how to handle mouse Right click in Qt

Sanath Reddy picture Sanath Reddy · Oct 25, 2013 · Viewed 19.3k times · Source

I am using QListView to show list of friends' names. When I click on a name it should select a name and show profile related information and on right click it needs to show context menu without selecting a name and showing profile information. The problem I am facing is on right click it is selecting the name and also shows the context menu. I don't want the name to be selected on the right click and only the context menu should be shown. I am using the Qt contextmenuevent like:

void contextMenuEvent(QContextMenuEvent *ce)
{
    QPoint pos = ce->pos();
    emit customContextMenuRequested(pos);
}   

This doesn't work and the above slot is never called.

Answer

Sanath Reddy picture Sanath Reddy · Oct 25, 2013

use mousePressEvent and handle the right click like the following

void QkFriendsListView::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton)
    {
        emit customContextMenuRequested(event->pos());
    }
    else
        QListView::mousePressEvent(event)
}