问题
please consider the following code:
#include <QWidget>
#include <iostream>
#include <QApplication>
class Widget : public QWidget
{
public:
void mousePressEvent(QMouseEvent* event)
{
std::cout << "mousePressEvent" < std::endl;
}
void mouseDoubleClickEvent(QMouseEvent* event)
{
std::cout << "mouseDoubleClickEvent" << std::endl;
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
Widget w;
w.show();
return app.exec();
}
Every time I process double click, the output is:
mousePressEvent
mouseDoubleClickEvent
This means Qt always call mousePressEvent as soon as one press proceed without waiting the second press. Is there a way to turn off this option, so that no mousePressEvent call will perform in case of double-click.
回答1:
I would bypass the handling of single click event (using a QTimer
) by the period of time equal to the QApplication::doubleClickInterval()
value. If double click is not happened during that time, I should handle "single click", otherwise the double click should be processed.
回答2:
As it says Qt Documentation: default implementation of mouseDoubleClickEvent
generates a normal mouse press event.
In qwidget.cpp
you can also find comment
mouseDoubleClickEvent() is called when the user double-clicks in the widget. If the user double-clicks, the widget receives a mouse press event, a mouse release event, (a mouse click event,) a second mouse press, this event and finally a second mouse release event.
回答3:
Why not just to increment by one in each event function? In case of a double click, the counter would increment two times by one.
A more generalized solution: eliminate the changes made by mousePressEvent
by subtracting the value it adds (can also be negative).
void mousePressEvent(QMouseEvent* event)
{
counter += singleClickStep;
}
void mouseDoubleClickEvent(QMouseEvent* event)
{
counter -= singleClickStep;
counter += doubleClickStep;
}
singleClickStep
and doubleClickStep
are the values by which you increment counter in each case.
Vahancho's answer solves the cases where you can't undo what was done by the single click, but the QApplication::doubleClickInterval()
might be too long. On the other hand, with my solution, you'll already see the value between the first and the second click on your widget.
来源:https://stackoverflow.com/questions/30262727/why-always-calling-mousepressevent-before-mousedoubleclickevent