qt c++ qpushbutton实现长按触发函数 且与单次区分
在Qt C++中,可以通过QTimer来实现长按触发函数,并与单次触发区分。
首先,在头文件中声明一个QTimer对象和一个QPushButton对象:
#include <QMainWindow>
#include <QTimer>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
private slots:
void onLongPress();
void onButtonClicked();
private:
QTimer *timer;
QPushButton *button;
};
然后,在源文件中初始化timer和button对象,并连接相应的槽函数:
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
timer = new QTimer(this);
timer->setInterval(100); // 设置定时器的间隔时间,单位为毫秒
timer->setSingleShot(true); // 设置定时器为单次触发
button = new QPushButton("Press and Hold", this);
button->setFixedSize(200, 100);
button->move(100, 100);
connect(timer, &QTimer::timeout, this, &MainWindow::onLongPress);
connect(button, &QPushButton::pressed, timer, &QTimer::start);
connect(button, &QPushButton::released, timer, &QTimer::stop);
connect(button, &QPushButton::clicked, this, &MainWindow::onButtonClicked);
}
void MainWindow::onLongPress()
{
qDebug() << "Long press triggered";
}
void MainWindow::onButtonClicked()
{
qDebug() << "Button clicked";
}
在上述代码中,timer对象的timeout信号与onLongPress槽函数连接,当定时器超过设定的间隔时间时,就会触发timeout信号,从而执行onLongPress槽函数。
button对象的pressed信号与timer对象的start槽函数连接,当按钮被按下时,定时器开始计时。button对象的released信号与timer对象的stop槽函数连接,当按钮释放时,定时器停止计时。
button对象的clicked信号与onButtonClicked槽函数连接,当按钮被点击时,执行onButtonClicked槽函数。
这样,当按钮被长按超过设定的间隔时间时,会触发onLongPress槽函数;当按钮被点击时,会触发onButtonClicked槽函数
原文地址: http://www.cveoy.top/t/topic/hC4J 著作权归作者所有。请勿转载和采集!