说明
Qt 界面设计时,经常遇到一个控件需要表示两种或者以上的状态。
可以使用状态机来实现。
代码如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QState>
#include <QStateMachine>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QState *state0 = new QState();
QState *state1 = new QState();
QState *state2 = new QState();
state0->assignProperty(ui->label_3,"text","open");
state0->assignProperty(ui->label_2,"text","close");
state0->assignProperty(ui->label,"text","close");
state1->assignProperty(ui->label_3,"text","close");
state1->assignProperty(ui->label_2,"text","open");
state1->assignProperty(ui->label,"text","close");
state2->assignProperty(ui->label_3,"text","close");
state2->assignProperty(ui->label_2,"text","close");
state2->assignProperty(ui->label,"text","open");
state0->addTransition(ui->pushButton,SIGNAL(clicked()),state1);
state1->addTransition(ui->pushButton,SIGNAL(clicked()),state2);
state2->addTransition(ui->pushButton,SIGNAL(clicked()),state0);
QStateMachine *statemachine = new QStateMachine();
statemachine->addState(state0);
statemachine->addState(state1);
statemachine->addState(state2);
statemachine->setInitialState(state0);
statemachine->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
运行验收