Differentiating between Left and right clicks in Q

2019-06-02 11:14发布

问题:

I have a QTableView, in which both Left- and right-click mouse result in some work.,

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? Kindly advise. Thanks.

EDIT

My code is set like 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?

回答1:

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();
    }
}