我需要随时检测何时在我的Qt5 / C ++应用程序中按下或释放右键。
到目前为止,我已对这些功能进行了编码:
void test::mousePressEvent(QMouseEvent *ev){
if(ev->buttons() == Qt::LeftButton){
qDebug() << "Left pressed";
ui->forceBar->setValue( 100 );
}
}
void test::mouseReleaseEvent(QMouseEvent *ev){
if(ev->button() == Qt::LeftButton){
ui->forceBar->setValue( 50 );
qDebug() << "Left released";
}
只有当点击不在pushbuttontest
时,它们才能正常工作。
问题是如果按钮发生在按钮上,我就不会得到这个事件。
答案 0 :(得分:2)
您必须从QPushButton
派生并覆盖这些事件处理程序。
class MyButton : public QPushButton
{
protected:
virtual void mousePressEvent(QMouseEvent* event);
virtual void mouseReleaseEvent(QMouseEvent* event);
};
void MyButton::mousePressEvent(QMouseEvent *ev){
if(ev->buttons() == Qt::LeftButton){
qDebug() << "Left pressed";
ui->forceBar->setValue( 100 );
}
}
void MyButton::mouseReleaseEvent(QMouseEvent *ev){
if(ev->button() == Qt::LeftButton){
ui->forceBar->setValue( 50 );
qDebug() << "Left released";
}
然后,将此按钮用作pushbuttontest
:
QPushButton* pushbuttontest = new MyButton();
或者,如果您想为许多小部件设置公共事件处理程序,则可以使用事件过滤器:
class test : public QWidget // the widget in which you want to capture all events
{
public:
bool eventFilter(QObject *watched, QEvent *e);
private:
QPushButton* pushbuttontest;
QLabel *myLabel;
};
bool test::eventFilter(QObject *watched, QEvent *e)
{
if (e->type() == QEvent::MouseButtonPress))
{
QMouseEvent* ev = (QMouseEvent*)e;
if(ev->buttons() == Qt::LeftButton){
qDebug() << "Left pressed";
ui->forceBar->setValue( 100 );
}
}
else if (e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* ev = (QMouseEvent*)e;
if(ev->buttons() == Qt::LeftButton){
qDebug() << "Left released";
ui->forceBar->setValue( 100 );
}
}
return false;// return true if you are finished handling the event. So, the default event handler will not be called.
}
然后,将eventFilter安装到您想要的小部件:
pushbuttontest = new QPushButton();
pushbuttontest->instalEventFilter(this); // this is the test class object which has our event filter code.
myLabel = new QLabel();
myLabel->installEventFilter(this);
等
请注意,我还没有编译此代码。它可能无法立即起作用。
了解更多信息:http://qt-project.org/doc/qt-4.8/eventsandfilters.html