溫馨提示×

C++實現幸運大抽獎(QT版)

c++
小云
174
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女