用Qt摇摇骰子

本文介绍了一个使用Qt编写的简单程序,通过点击按钮来模拟摇骰子的过程。程序包括一个DiceWidget类,它继承自QWidget,并包含一个按钮用于触发摇骰子的动作。文章详细展示了DiceWidget的实现过程,包括如何响应按钮点击事件并更新骰子的显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有段时间没有碰Qt了,小小地写个程序温习下。

程序实现的功能就是点击按钮开始摇动骰子,再次点击停止摇,得到数字。

首先,定义一个DiceWidget类,继承QWidget。

DiceWidget提供一个按钮rollButton供用户点击摇骰子,并将该按钮的clicked()信号连接到DiceWidget的roll()槽。

dice.h代码如下:

#ifndef DICE_H #define DICE_H #include <QWidget> class QLabel; class QPushButton; class QVBoxLayout; class QMovie; class DiceWidget : public QWidget { Q_OBJECT public: DiceWidget(QWidget *parent = 0); ~DiceWidget(); private slots: void roll(); private: bool rollingFlag; QString bgfile; QMovie *bgMovie; QPushButton *rollButton; QLabel *diceLabel; QVBoxLayout *layout; }; #endif // DICE_H

在dice.cpp中完成对DiceWidget的定义。

当rollButton被点击后,clicked()信号发射到roll()槽中。首先判断当前状态是在摇还是已经停止了,如果在摇就停止gif图片的播放,生成一个1-6的随机数,然后根据随机数修改显示图片。

#include "dice.h" #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include <QPixmap> #include <QMovie> #include <QtGlobal> #include <QTime> DiceWidget::DiceWidget(QWidget *parent) : QWidget(parent){ rollingFlag = false; bgfile = ":/images/dice1.png"; bgMovie = new QMovie(":/images/dice_rolling.gif"); diceLabel = new QLabel; diceLabel->setMovie(bgMovie); diceLabel->setPixmap(QPixmap(bgfile)); rollButton = new QPushButton(tr("Roll")); layout = new QVBoxLayout; layout->addWidget(diceLabel); layout->addWidget(rollButton); setLayout(layout); connect(rollButton, SIGNAL(clicked()), this, SLOT(roll())); } DiceWidget::~DiceWidget(){ delete bgMovie; delete diceLabel; delete rollButton; delete layout; } void DiceWidget::roll(){ if(!rollingFlag){ rollingFlag = true; rollButton->setText(tr("Stop")); diceLabel->setMovie(bgMovie); bgMovie->start(); qsrand(QDateTime::currentDateTime().toTime_t()); }else{ rollingFlag = false; rollButton->setText(tr("Roll")); diceLabel->setMovie(bgMovie); bgMovie->stop(); int k = qrand() % 6 + 1; bgfile.replace(13, 1, QChar(k+48)); diceLabel->setPixmap(bgfile); } }

最后,运行程序。

#include <QApplication> #include "dice.h" int main(int argc, char *argv[]){ QApplication app(argc, argv); DiceWidget dice; dice.show(); return app.exec(); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值