Qt点名器
项目已开源,点击跳转
废话不多说,直接上代码。
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(qt-caller)
find_package(QT NAMES Qt6 Qt5 COMPONENTS Widgets REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_executable(qtCaller main.cpp widget.cpp widget.h)
target_link_libraries(qtCaller PRIVATE Qt${QT_VERSION_MAJOR}::Widgets)
main.cpp
#include <QWidget>
#include <QApplication>
#include <QBoxLayout>
#include <QPushButton>
#include <QLabel>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Widget win;
//设置窗口大小
win.setMinimumSize(380,200);
win.show();
return app.exec();
}
widget.h
#include <QWidget>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QList>
#include <QRandomGenerator>
#include <QTimer>
#include <qapplication.h>
#include <qfont.h>
#include <qglobal.h>
#include <qgridlayout.h>
#include <qnamespace.h>
#include <qobjectdefs.h>
#include <qwindowdefs.h>
class Widget : public QWidget
{
public:
Widget();
~Widget();
private:
//声明控件
QGridLayout *layout = new QGridLayout(this);
QPushButton *pushButton = new QPushButton("开始");
QLabel *label = new QLabel("预备备");
//名单读取
bool loadtxt();
qint8 num = 0;
QList<QString> namelists;
//点名
void caller();
QTimer *timer = new QTimer(this);
qint8 j = 0;
private slots:
//按钮事件
void on_pushButton_clicked(bool checked);
//播放名单
void play_lists();
};
widget.cpp
#include "widget.h"
#include <QDebug>
#include <qdebug.h>
#include <qpushbutton.h>
#include <qrandom.h>
#include <qtimer.h>
#include <qwidget.h>
Widget::Widget()
{
label->setAlignment(Qt::AlignCenter);
label->setStyleSheet("border: 2px solid blue");
label->setScaledContents(true);
//设置字体大小
QFont font;
font.setPointSize(36);
label->setFont(font);
//添加控件至界面布局
layout->addWidget(label, 0, 0, 1, 2);
layout->addWidget(pushButton, 1, 0, 1, 2);
//加载名单
if(!loadtxt())
qDebug() << "读取失败";
else
qDebug() << "读取成功";
//连接按钮事件
connect(pushButton,&QPushButton::clicked,this,&Widget::on_pushButton_clicked);
//循环显示名单
connect(timer,&QTimer::timeout,this,&Widget::play_lists);
timer->start(100);
}
Widget::~Widget()
{
//释放内存
delete(pushButton);
delete(label);
delete(layout);
}
void Widget::on_pushButton_clicked(bool checked)
{
if(checked == true)
{
pushButton->setText("开始");
caller();
pushButton->setCheckable(false);
}
else
{
pushButton->setText("停止");
pushButton->setCheckable(true);
}
}
bool Widget::loadtxt(void)
{
QFile file("namelists.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QTextStream nameFile(&file);
while (!nameFile.atEnd()) {
namelists << nameFile.readLine();
num++;
}
return true;
}
void Widget::caller()
{
qint32 i = QRandomGenerator::global()->bounded(0, num);
label->setText(namelists[i]);
}
void Widget::play_lists()
{
if(pushButton->isCheckable())
label->setText(namelists[j++]);
if(j >= num)
j = 0;
}
效果图
(screenshot)