我正在构建一个使用 QTimer 显示交通信号灯图像的小程序。所以我设置了我的计时器,一切正常。但我不知道,每次达到定时器间隔时,如何让机器人灯 ->show() 和 ->hide()。我可能有这一切都错了,我还在学习,所以请指教。
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void timer();
QTimer *mytimer;
private:
Ui::MainWindow *ui;
int timerValue;
private slots:
void showGreen();
void showYellow();
void showRed();
void on_startButton_clicked();
};
#endif // MAINWINDOW_H
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->green->setVisible(false);
ui->yellow->setVisible(false);
ui->red->setVisible(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::timer(){
ui->green->setVisible(true);
mytimer = new QTimer(this);
connect(mytimer,SIGNAL(timeout()),this,SLOT(showYellow()));
mytimer->start(timerValue = (ui->spinBox->value())*1000);
}
void MainWindow::showYellow(){
ui->yellow->setVisible(true);
mytimer = new QTimer(this);
connect(mytimer,SIGNAL(timeout()),this,SLOT(showRed()));
mytimer->start(timerValue);
}
void MainWindow::showRed(){
ui->red->setVisible(true);
mytimer = new QTimer(this);
connect(mytimer,SIGNAL(timeout()),this,SLOT(showGreen));
mytimer->start(timerValue);
}
void MainWindow::showGreen(){
ui->green->setVisible(true);
mytimer = new QTimer(this);
connect(mytimer,SIGNAL(timeout()),this,SLOT(showYellow()));
mytimer->start(timerValue);
}
void MainWindow::on_startButton_clicked()
{
timer();
ui->startButton->setEnabled(false);
}
我还禁用了单击时的“开始”按钮,因此计时器不能运行两次。
因此,在主窗口 UI 上,我基本上有一个 Spinbox,它接受用户的输入,这是我将其传递给 Qtimer 的时间,然后我有 3 个带有红色绿色黄色灯光的图像,它们必须在间隔中显示和隐藏. 所以我创建了几乎类似于手动循环的东西。Qtimer 启动并显示绿色,然后进入 ShowYellow Slot,然后显示 Red 插槽,所以现在,它假设进入 Green 插槽然后变为黄色,但它不会再次进入 Green。
谁能告诉我为什么不。