QPushButton down signal
-
Hello Qt devs!
I'm trying to make an application, which should enable the user to increment or decrement a variable by using two QPushButtons called "up" and "down". When the user presses the "up" button, the variable is incremented like intended. I would like to add a feature where if the user holds down the "up" button, then the variable will continue increasing. The longer the user holds down the button, the greater the incrementation steps should be.
But I guess my main question is: what signal from QPushButton is sent when a button is held down?
Thank you for your time!
-
One of the solution:
@void MainWindow::on_pushButton_pressed()
{
int i = 0;
while (pushButton->isDown()) {
qDebug()<<i++;
QApplication::processEvents();
}
}@ -
A button has several signals, e.g.:
-
A little more details on Gerolf's suggestion:
Connect the pressed signal to a slot, do the increment, start a timer with a longer timeout, when the timer fires do another increment, restart the timer with a shorter timeout and redo that. Connect the release signal to the stop slot of the timer. -
Thank you so much for your help!
A special thanks to Volker for spelling it out to me! Dunno if that's the correct saying :)
This is how it looks - in a simplified version:
@void MyClass::myFunction() {
number++;
QTimer::singleShot(200, this, SLOT(myFunction()));
}@Thank you so much for your time!
-
-
This code works for me:
The ui contains a QPushButton (pushButton) and a QLabel (label), you can easily create it with Qt Designer.
buttonincrementer.h
@
#ifndef BUTTONINCREMENTER_H
#define BUTTONINCREMENTER_H#include <QDialog>
class QTimer;
namespace Ui {
class ButtonIncrementer;
}class ButtonIncrementer : public QDialog
{
Q_OBJECTpublic:
explicit ButtonIncrementer(QWidget *parent = 0);
~ButtonIncrementer();protected:
protected slots:
void buttonPressed();
void buttonReleased();
void doIncrement();private:
Ui::ButtonIncrementer *ui;
QTimer *timer;
int timerTimeout;
int number;
};#endif // BUTTONINCREMENTER_H
@buttonincrementer.cpp
@
#include "buttonincrementer.h"
#include "ui_buttonincrementer.h"
#include <QTimer>ButtonIncrementer::ButtonIncrementer(QWidget *parent) :
QDialog(parent),
ui(new Ui::ButtonIncrementer)
{
ui->setupUi(this);
number = 0;
timerTimeout = 0;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(doIncrement()));
connect(ui->pushButton, SIGNAL(pressed()), this, SLOT(buttonPressed()));
connect(ui->pushButton, SIGNAL(released()), this, SLOT(buttonReleased()));
}ButtonIncrementer::~ButtonIncrementer()
{
delete ui;
}void ButtonIncrementer::buttonPressed()
{
timerTimeout = 2000;
doIncrement();
}void ButtonIncrementer::buttonReleased()
{
timer->stop();
}void ButtonIncrementer::doIncrement()
{
++number;
ui->label->setText(QString("Value: %1").arg(number));
if(timerTimeout > 50)
timerTimeout = timerTimeout / 2;
timer->start(timerTimeout);
}
@