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

一个人想着一个人 提交于 2020-03-16 09:02:51

问题


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){.....}

回答1:


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 ?




回答2:


for "connect" use this:

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

define a global flag:

public:
Qt::MouseButton mouseClickedBtnFlag;

and then reimplement "mouseReleaseEvent":

CGuiMainwindow::mouseReleaseEvent ( QMouseEvent * event )
{
mouseClickedBtnFlag = event->button();
}

and then:

void CGuiMainwindow::SlotItemClicked(QTreeWidgetItem *item, int column)
{    
 if (mouseClickedBtnFlag == Qt::LeftButton)              
 { return; }              

 if (mouseClickedBtnFlag == Qt::RightButton)              
 {              
    ......              
 }
}



回答3:


Qt::MouseButtons is a QFlags type. You can't test it with == operator. Use & operator for testing:

if(QApplication::mouseButtons() & Qt:LeftButton) {
...
}


来源:https://stackoverflow.com/questions/3090187/how-to-tell-the-mouse-button-using-qapplicationmousebuttons-in-a-click-slo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!