Tee käyttöliittymä, jossa on painike nimeltä  switchState ja kolme QLabel-elementtiä nimiltään red, yellow ja green. mainwindow.cpp näyttää seuraavalta:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStateMachine>
#include <QFinalState>
 
MainWindow::MainWindow(QWidget *parent) :
 QMainWindow(parent),
 ui(new Ui::MainWindow)
{
 ui->setupUi(this);
 
 QStateMachine *trafficLights=new QStateMachine(this);
 QState *red=new QState(trafficLights);
 QState *yellow=new QState(trafficLights);
 QState *green=new QState(trafficLights);
 
 trafficLights->addState(red);
 trafficLights->addState(yellow);
 trafficLights->addState(green);
 trafficLights->setInitialState(red);
 trafficLights->start();
 
 QString grey="background-color:grey";
 
 red->assignProperty(ui->red,"styleSheet","background-color:red");
 yellow->assignProperty(ui->yellow,"styleSheet","background-color:yellow");
 green->assignProperty(ui->green,"styleSheet","background-color:green");
 
 // set all other lights to grey
 yellow->assignProperty(ui->red,"styleSheet",grey);
 green->assignProperty(ui->red,"styleSheet",grey);
 red->assignProperty(ui->green,"styleSheet",grey);
 yellow->assignProperty(ui->green,"styleSheet",grey);
 red->assignProperty(ui->yellow,"styleSheet",grey);
 green->assignProperty(ui->yellow,"styleSheet",grey);
 
 red->addTransition(ui->switchState,SIGNAL(clicked()),yellow);
 yellow->addTransition(ui->switchState,SIGNAL(clicked()),green);
 green->addTransition(ui->switchState,SIGNAL(clicked()),red);
 
}
 
MainWindow::~MainWindow()
{
 delete ui;
}
 
  • No labels
You must log in to comment.