PDA

View Full Version : long mouse press event



tonylin0826
26th September 2012, 14:46
Hi, if there is any way i can detect a mouse long press event in qt. Because i want to keep drawing a different circle on the mainwindow while my mouse is down. thanks:))

wysota
26th September 2012, 15:08
Intercept mousePressEvent and start a timer there. Intercept a mouseMoveEvent or mouseReleaseEvent (depending on what you want to do) and check the timer. If it exceeds a predefined threshold, you have a long press, otherwise you have a short press.

tonylin0826
26th September 2012, 15:17
thanks, but i need to have a long press that can press as long time as i want. can a timer do that?

wysota
26th September 2012, 15:59
The timer doesn't care. It just measures time. If I understand you right and you want to keep increasing the circle diameter as the user is keeping the button down, you can start a timer to some short interval like 25ms and each time it fires, increase the diameter a bit. When the button is released, stop the timer and draw the final circle.

tonylin0826
27th September 2012, 15:38
thanks, but i need to draw the circle while i am pressing the left button not release the button. Can you teach me how?

wysota
27th September 2012, 16:24
thanks, but i need to draw the circle while i am pressing the left button not release the button.

That's what I meant. You are drawing the circle while the button is pressed but when it is released, you need to make your item permanent.

Here is a simple example that uses QGraphicsView:

#include <QtGui>

class View : public QGraphicsView {
Q_OBJECT
public:
View() : QGraphicsView() {
current = 0;
radius = 0;
t.setInterval(10);
connect(&t, SIGNAL(timeout()), this, SLOT(incDiameter()));
}

void mousePressEvent(QMouseEvent *me) {
current = new QGraphicsEllipseItem;
radius = 5;
QRect r;
r.setWidth(2*radius);
r.setHeight(2*radius);
r.moveCenter(mapToScene(me->pos()).toPoint());
current->setRect(r);
scene()->addItem(current);
t.start();
}
void mouseReleaseEvent(QMouseEvent *me) {
t.stop();
current = 0;
}
private slots:
void incDiameter() {
QRect r;
radius++;
r.setWidth(2*radius);
r.setHeight(2*radius);
r.moveCenter(current->rect().center().toPoint());
current->setRect(r);
}
private:
QGraphicsEllipseItem *current;
QTimer t;
int radius;
};

#include "main.moc"


int main(int argc, char **argv) {
QApplication app(argc, argv);
View view;
view.setScene(new QGraphicsScene(0,0,600,400));
view.show();
return app.exec();
}