qtmouseeventqtableview

Differentiating between left and right mouse clicks in QTableView


I have a QTableView, in which both left and right mouse clicks result in some action.

The right click should launch a context menu, and the left should open another process.

I use the following connects for this purpose in my QMainWindow:

connect(Table , SIGNAL( customContextMenuRequested( const QPoint& ) ),this, SLOT( tableContextMenu( const QPoint& ) ) );
 connect(Table , SIGNAL (clicked ( const QModelIndex&)), this, SLOT(test()));

The Problem is fairly simple to see. Since I use clicked() signal to capture the left click — the right click is captured too. So, if I click on the right click button, along with the context menu, the action reserved for the left click occurs as well.

How do I avoid this?

Table = new QTableView(this);
TableLayout *t = new TableLayout();
Table->setModel(t);
Table->setContextMenuPolicy(Qt::CustomContextMenu);
connect(Table , SIGNAL( customContextMenuRequested( const QPoint& ) ),this, SLOT( tableContextMenu( const QPoint& ) ) );

This is how I do it for the right click context menu, and all are defined in P14MainWindow constructor, which is an object of QMainWindow.

Now where exactly should I reimplement MouseReleaseEvent?


Solution

  • To launch a context menu reimplement QTableView::contextMenuEvent(QContextMenuEvent* e), and similarly reimplement QTableView::mouse...Event(QMouseEvent* event) to catch mouse events.

    Then use QTableView::indexAt(const QPoint& pos) const to return the model index at the click site.

    Here is an example of the left click handling:

    void Table::mouseReleaseEvent(QMouseEvent* event)
    {
        QTableView::mouseReleaseEvent( event );
    
        if ( event->button == Qt::LeftButton ) {
            test();
        }
    }