温馨提示×

C++实现幸运大抽奖(QT版)

c++
小云
126
2023-08-15 13:39:32
栏目: 编程语言

以下是一个使用C++和QT库实现的幸运大抽奖程序:

#include <QApplication>
#include <QWidget>
#include <QLayout>
#include <QLabel>
#include <QPushButton>
#include <QTimer>
#include <QTime>
class LuckyDraw : public QWidget {
Q_OBJECT
public:
LuckyDraw(QWidget *parent = nullptr) : QWidget(parent) {
setFixedSize(400, 200);
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *titleLabel = new QLabel("幸运大抽奖", this);
titleLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(titleLabel);
resultLabel = new QLabel("", this);
resultLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(resultLabel);
startButton = new QPushButton("开始抽奖", this);
layout->addWidget(startButton);
connect(startButton, &QPushButton::clicked, this, &LuckyDraw::startDraw);
}
private slots:
void startDraw() {
startButton->setEnabled(false);
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &LuckyDraw::showResult);
timer->start(100);
}
void showResult() {
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
int random = qrand() % 100;
resultLabel->setText(QString("中奖号码:%1").arg(random));
}
private:
QLabel *resultLabel;
QPushButton *startButton;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
LuckyDraw luckyDraw;
luckyDraw.show();
return app.exec();
}
#include "main.moc"

在这个程序中,我们定义了一个LuckyDraw类作为主窗口部件,继承自QWidget。在构造函数中,我们设置了窗口的固定大小,并创建了一个垂直布局和标题标签、结果标签和开始抽奖按钮,并将它们添加到布局中。点击开始抽奖按钮后,将禁用按钮,并创建一个定时器,在定时器的timeout信号中调用showResult函数来显示中奖结果。

showResult函数中,我们使用QTime获取当前时间,并根据当前毫秒数设置随机数生成器的种子,然后使用qrand函数生成一个0到99的随机数,并将其作为中奖号码显示在结果标签中。

main函数中,我们创建一个QApplication对象,然后创建一个LuckyDraw对象,并显示出来。

需要注意的是,由于使用了QT的信号和槽机制,我们需要在程序的结尾使用#include "main.moc"来处理元对象编译器生成的moc文件。

0