我在实施时间方面遇到了问题。我想做的就是运行:
//relay 1 power cycle
void MainWindow::relay1PCycle()
{
relay1High();
while (true){
QTimer::singleShot(750, this, SLOT(relay1Low()));
QTimer::singleShot(750, this, SLOT(relay1High()));
}
}
按下按钮时。
//power cycle button
void MainWindow::on_pushButton_3_toggled(bool checked)
{
if (checked){
//run relay1PCycle as a thread.
}
else{
//Terminate relay1PCycle thread.
}
}
然而,迄今为止我所尝试过的所有内容都是失败的。
正确的方法是什么?
由于
答案 0 :(得分:0)
他们想要实现的任务不是阻塞,因此没有必要使用线程,只有具有足够逻辑的计时器。为简单起见,我们将该任务分配给下一个类:
<强> relaycontroller.h 强>
#ifndef RELAYCONTROLLER_H
#define RELAYCONTROLLER_H
#include <QObject>
#include <QTimer>
#include <QDebug>
class RelayController : public QObject
{
Q_OBJECT
public:
explicit RelayController(QObject *parent = 0):QObject(parent){
timer = new QTimer(this);
state = false;
timer->setInterval(750);
//old style
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
//new style
//connect(timer, &QTimer::timeout, this, &RelayController::onTimeout);
}
void start(){
qDebug()<<"timer";
timer->start();
}
void stop(){
timer->stop();
}
void relayLow(){
//code here: relay off
qDebug()<<"low";
}
void relayHigh(){
//code here: relay on
qDebug()<<"high";
}
private slots:
void onTimeout(){
if(state)
relayHigh();
else
relayLow();
state = !state;
}
private:
QTimer *timer;
bool state;
};
#endif // RELAYCONTROLLER_H
然后在按下的插槽中创建并使用对象:
<强> mainwindow.h 强>
private:
RelayController *controller;
<强> mainwindow.cpp 强>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
controller = new RelayController(this);
ui->pushButton_3->setCheckable(true);
}
void MainWindow::on_pushButton_toggled(bool checked)
{
if(checked)
controller->start();
else
controller->stop();
}