新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

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

发布时间:2023-08-16 07:52:31

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

以下是一个使用C++和QT库实现的荣幸大抽奖程序:
```cpp
#include
#include
#include
#include
#include
#include
#include
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文件。