Qt之QTimer Posted on 2019-05-12 | Edited on 2021-12-13 | Views: Symbols count in article: 2.1k | Reading time ≈ 2 mins. 第10篇 Qt5基础(十)Qt定时器和随机数 QT之 QTimer使用方法 Qt 之 QProgressBar 效果图如下,定时器设置为100ms触发,进度条也随之滚进。 MainWindow.h #pragma once#include <QtWidgets/QMainWindow>#include "ui_MainWindow.h"#include <QTimer>#include <QProgressBar>class MainWindow : public QMainWindow{ Q_OBJECTpublic: MainWindow(QWidget *parent = Q_NULLPTR);private: Ui::MainWindowClass ui; QTimer *timer_; QProgressBar *progress_;private slots: void UpdateProgress();}; MainWindow.cpp #include "MainWindow.h"#include <QPushButton>#include <QLayout>MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); timer_ = new QTimer(this); timer_->setInterval(100); progress_ = new QProgressBar(this); progress_->setRange(0, 100); progress_->setValue(50); QPushButton *okBtn = new QPushButton(this); okBtn->setText(tr("ok")); QPushButton *cancelBtn = new QPushButton(this); cancelBtn->setText(tr("cancel")); QHBoxLayout *btnLayout = new QHBoxLayout(); btnLayout->addWidget(okBtn); btnLayout->addWidget(cancelBtn); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->addWidget(progress_); mainLayout->addLayout(btnLayout); QWidget *widget = new QWidget(this); //setCentralWidget(widget); //centralWidget()->setLayout(mainLayout); widget->setLayout(mainLayout); setCentralWidget(widget); connect(okBtn, &QPushButton::clicked, timer_, static_cast<void (QTimer::*)()> (&QTimer::start)); connect(cancelBtn, &QPushButton::clicked, timer_, &QTimer::stop); connect(timer_, &QTimer::timeout, this, &MainWindow::UpdateProgress);}void MainWindow::UpdateProgress() { int curVal = progress_->value(); ++curVal; if (curVal >= 100) { curVal = 0; } progress_->setValue(curVal);} main.cpp #include "MainWindow.h"#include <QtWidgets/QApplication>int main(int argc, char *argv[]){ QApplication a(argc, argv); MainWindow w; w.show(); return a.exec();}