QTimer計時器和QTimerEvent的應用
阿新 • • 發佈:2021-07-07
QTimer是一個計時器,現在把有用的東邪貼出來
//mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QTime> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: void timerEvent(QTimerEvent *); explicit MainWindow(QWidget *parent = nullptr);~MainWindow(); signals: void timeout(); public slots: void printFile(); public: void creatConnection(); void Init(); private: Ui::MainWindow *ui; QTimer* printfpTimer;//QTimer int id1; int id2; int num = 0; }; #endif // MAINWINDOW_H //mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QTimerEvent> #include <QTimer> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); printfpTimer = new QTimer(this); id1 = startTimer(5000); id2 = startTimer(2000); printfpTimer->start(1000); //printfpTimer->setInterval(100); creatConnection(); printfpTimer->setSingleShot(false);//預設就是false,這行也可以不寫 } void MainWindow::creatConnection() { connect(printfpTimer, SIGNAL(timeout()), this, SLOT(printFile())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::printFile() { static int num3=0; ui->lineEdit->setText(QString::number(num3++)); } void MainWindow::timerEvent(QTimerEvent *event) { if(event->timerId() == id1) ui->label_1->setText(QString::number(num++)); static int num2=0; if(event->timerId() == id2) ui->label_2->setText(QString::number(num2++)); } //.cpp檔案--使用singleShot靜態函式,此時不需要例項化QTimer //QTimer::singleShot(10000, this, SLOT(onZipTodayFile())); //main.cpp #include "mainwindow.h" #include <QApplication> #include "Application.h" int main(int argc, char *argv[]) { //QApplication a(argc, argv); CApplication a( argc, argv ); MainWindow w; w.show(); return a.exec(); }