Qt – How to tell the mouse button using QApplication::mouseButtons() in a “click” slot

mouseclick-eventqtqt4right-clicksignals-slots

I have a QMainWindow, and want to handle the "clicked" signal from a smaller widget (such as tableview) inside it.

Originally I connect the signal to a slot of this QMainWindow, this is the most common approach.
Now I need to tell which mouse button is clicked, and do different things for left and right button, I found that the "clicked" signal don't have the mouse event information.

I tried to implement the "mousePressEvent" function,but there are still some problem. if the mouse action is acted on the smaller widget, the MainWindow won't go into its mousePressEvent.

Some document says that we can tell the button by QQApplication::mousebuttons()

http://bugreports.qt-project.org/browse/QTBUG-1067

and I also found some sample code. However, this is for "press event", but I want to get the mouse button for "click event".
Follows is the sample code :

connect(moduleTree,SIGNAL(itemPressed(QTreeWidgetItem *, int)),this,SLOT(SlotItemClicked(QTreeWidgetItem *, int)));

void CGuiMainwindow::SlotItemClicked(QTreeWidgetItem *item, int column)

{
     if (qApp->mouseButtons() == Qt::LeftButton)
     { return; }

     if (qApp->mouseButtons() == Qt::RightButton)
     {
        ......
     }
}

When I try to do this, neither of the 2 if statements will be satisfied, I don't know why. the qApp->mouseButtons() always return 0, how can I get the clicked mouse button by QApplication::mouseButtons?

In my code, the slot looks like that :

void clickItem( const QModelIndex & idx){.....}

Best Answer

You get 0 becouse clicked is emited after mouse release, not at mouse press. What do you want to achieve ? Maybe try settings on you widget contextMenuPolicy to custom, and than connect to signal contextMenuRequested (for the right click) and clicked for the left click ?

Related Topic