gpt4 book ai didi

c++ - Qt 使用 isAutoRepeat() 处理 QPushButton Autorepeat() 行为

转载 作者:行者123 更新时间:2023-11-28 05:51:08 24 4
gpt4 key购买 nike

我是 QT 的新手,正在制作一个与预先存在的图形用户界面交互的小部件。我想让我的小部件在用户按下按钮时连续输出一个信号,然后在释放按钮时连续输出另一个信号。

通过启用自动重复,我可以让小部件在用户按下按钮时输出我的信号,但是,输出信号在 pressed() 和 released() 之间切换。例如。

<>输出:* 按下信号* 释放信号* 按下信号* 释放信号

我看到这个问题被问到关于 keyPressEvents 的问题但我不确定如何访问按钮的 isAutoRepeat()。有人可以就此给我建议吗?

最佳答案

一种方法是您可以使用计时器对象来实现此目的。下面是示例,当按下和释放按钮时将运行 2 个插槽。代码注释会详细说明。当按下并释放按钮时,文本框将以毫秒为单位显示连续时间。定时器是一个对象,它将在给定的时间间隔内发出 timeout() 信号。我们需要在按钮按下/释放信号中停止和启动备用计时器。此应用程序使用 QT Creator“QT Widgets Application”向导创建。希望对您有所帮助。

//头文件

    class MainWindow : public QMainWindow{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
//Button slots
void on_pushButton_pressed(); //Continuous press
void on_pushButton_released(); //Continuous release
void on_pushButton_2_clicked(); //stop both the timer
//QTimer timeout actions
void timer1_action();
void timer2_action();

private:
Ui::MainWindow *ui;
//Timer object
QTimer *t1, *t2;
//Date time object for testing
QDateTime dt1,dt2;
};

//CPP文件

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){
ui->setupUi(this);
//Parent object will take care of the deallocation of the 2 timer objects
t1 = new QTimer(this);
t2 = new QTimer(this);
//Interval to the timer object
t1->setInterval(10);
t2->setInterval(10);
//Signal slot for the timer
this->connect(t1,SIGNAL(timeout()),this,SLOT(timer1_action()));
this->connect(t2,SIGNAL(timeout()),this,SLOT(timer2_action()));
}
MainWindow::~MainWindow(){
delete ui;
}
void MainWindow::on_pushButton_pressed(){
//starting and stoping the timer
t2->stop();
t1->start();
//date time when pressed
dt1 = QDateTime::currentDateTime();
}
void MainWindow::on_pushButton_released(){
//starting and stoping the timer
t1->stop();
t2->start();
//date time when pressed
dt2 = QDateTime::currentDateTime();
}
void MainWindow::timer1_action(){
ui->txtTimer1->setPlainText("Button Pressed for " + QString::number(dt1.msecsTo(QDateTime::currentDateTime())) + " Milli Seconds");
}
void MainWindow::timer2_action(){
ui->txtTimer2->setPlainText("Button Released for " + QString::number(dt2.msecsTo(QDateTime::currentDateTime())) + " Milli Seconds");
}
void MainWindow::on_pushButton_2_clicked(){
//stoping both the timer
t1->stop();
t2->stop();
}

enter image description here

关于c++ - Qt 使用 isAutoRepeat() 处理 QPushButton Autorepeat() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35228598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com