1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
class TrafficLightWidget : public QWidget {
public:
TrafficLightWidget(QWidget *parent = nullptr) : QWidget(parent) {
// Set up the layout
QGridLayout *layout = new QGridLayout(this);
// Create the labels to display the traffic light colors
greenLabel = new QLabel(this);
yellowLabel = new QLabel(this);
redLabel = new QLabel(this);
// Create the button to start the traffic light
startButton = new QPushButton("Start", this);
// Add the labels and button to the layout
layout->addWidget(greenLabel, 0, 0);
layout->addWidget(yellowLabel, 0, 1);
layout->addWidget(redLabel, 0, 2);
layout->addWidget(startButton, 1, 0, 1, 3);
// Connect the start button to the startTrafficLight() slot
connect(startButton, &QPushButton::clicked, this, &TrafficLightWidget::startTrafficLight);
}
private slots:
void startTrafficLight() {
// Disable the button to prevent changing the time interval during execution
startButton->setEnabled(false);
// Set the default time interval in milliseconds (change this to desired interval)
int timeInterval = 2000;
// Load the image files for green, yellow, and red lights
QPixmap greenPixmap("green.jpg");
QPixmap yellowPixmap("yellow.jpg");
QPixmap redPixmap("red.jpg");
// Set the images for the labels
greenLabel->setPixmap(greenPixmap);
yellowLabel->setPixmap(yellowPixmap);
redLabel->setPixmap(redPixmap);
// Hide the yellow and red lights at the beginning
yellowLabel->hide();
redLabel->hide();
// Create a QTimer to handle the time intervals
QTimer *timer = new QTimer(this);
// Connect the timer's timeout signal to the updateTrafficLight() slot
connect(timer, &QTimer::timeout, this, &TrafficLightWidget::updateTrafficLight);
// Start the timer with the specified time interval
timer->start(timeInterval);
}
void updateTrafficLight() {
// Toggle the visibility of the lights
if (greenLabel->isVisible()) {
greenLabel->hide();
yellowLabel->show();
} else if (yellowLabel->isVisible()) {
yellowLabel->hide();
redLabel->show();
} else if (redLabel->isVisible()) {
redLabel->hide();
greenLabel->show();
}
}
private:
QLabel *greenLabel;
QLabel *yellowLabel;
QLabel *redLabel;
QPushButton *startButton;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
widget.resize(110, 300);
widget.show();
return app.exec();
}
|