Qt 状态机使用

说明

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;
}


运行验收

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值