一種方法是您可以使用計時器對象來實現此目的。下面是這個例子,當按鈕被按下並釋放時,它將運行2個插槽。代碼評論將詳細解釋。當按下按鈕&發佈時,文本框將以毫秒顯示連續時間。 Timer是一個會在給定時間間隔內發出timeout()信號的對象。我們需要停止並按下按鈕/釋放信號啓動備用計時器。此應用程序使用QT Creator「QT Widgets應用程序」嚮導創建。 希望得到這個幫助。
//頭文件
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();
}
你好得多編寫自定義按鈕。 – user3528438
你可以解釋一個連續信號發佈的目的嗎?什麼組件需要知道按鈕狀態(即描述預先存在的gui要求)?你是否意識到這種機制意味着按鈕每次都會觸發一個或另一個信號? [你可以解釋X而不是Y?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – UmNyobe