Qt Button implements button long press event
background
Recently, the project encountered a requirement. Press and hold the mouse button to send data continuously, and release the mouse to leave immediately.
After thinking for a while, there are probably several ideas (just ideas, different can be realized)
1. Rewrite the mouse event and realize it through mouse detection.
2. Timer trigger implementation.
3. Realize through a certain parameter or check command.
research
- QT button class and timer application
- 【QT】Timer
- Qt actual combat case (45) - using QPushButton to realize button long press event
Type 3
The third one meets my needs, try with the third one
widget.cpp source file
ui->pushButton->setAutoRepeat(true); //启用长按
ui->pushButton->setAutoRepeatDelay(400);//触发长按的时间
ui->pushButton->setAutoRepeatInterval(50);//长按时click信号间隔
connect(ui->pushButton,&QPushButton::clicked,[&]{
qDebug()<<i++;
ui->horizontalSlider->setValue(i);
if(i>=100)i=100;//将最大值控制在100
});
The effect does work.
best way
But I took a closer look at the UI interface and found that it doesn’t have to be so troublesome. Check a box to solve the problem.
Qt’s QpushButton realizes the long-press state trigger function
summary
From requirement decomposition to realization, find the best method, get twice the result with half the effort! Reach the second-level realm of understanding strength!
Triple Realm "Recruiting familiarity, understanding strength, and gods"