代码 qtimer_thread.cpp

    1. #include "qtimer_thread.h"
    2. #include "ui_qtimer_thread.h"
    3. Qtimer_thread::Qtimer_thread(QWidget *parent)
    4. : QWidget(parent)
    5. , ui(new Ui::Qtimer_thread)
    6. {
    7. ui->setupUi(this);
    8. btn = new QPushButton(this);
    9. connect(btn, SIGNAL(clicked()),
    10. this, SLOT(creat_thread()));
    11. }
    12. void Qtimer_thread::thread()
    13. {
    14. std::cout << "sleep" << std::endl;
    15. }
    16. void Qtimer_thread::creat_thread()
    17. {
    18. tim = new QTimer(this);
    19. connect(tim, SIGNAL(timeout()), this, SLOT(thread()));
    20. tim->start(1000);
    21. }
    22. Qtimer_thread::~Qtimer_thread()
    23. {
    24. std::cout << "Qtimer_thread::~Qtimer_thread()" << std::endl;
    25. thread_exit = 0;
    26. delete btn;
    27. delete tim;
    28. delete ui;
    29. }
    30. void Qtimer_thread::closeEvent(QCloseEvent *event)
    31. {
    32. std::cout << "closeEvent execed" << std::endl;
    33. thread_exit = 0;
    34. }

    代码 qtimer_thread.h

    1. #ifndef QTIMER_THREAD_H
    2. #define QTIMER_THREAD_H
    3. #include <QWidget>
    4. #include <QPushButton>
    5. #include <iostream>
    6. #include <QTimer>
    7. #include <QCloseEvent>
    8. extern "C"
    9. {
    10. #include <unistd.h>
    11. }
    12. QT_BEGIN_NAMESPACE
    13. namespace Ui { class Qtimer_thread; }
    14. QT_END_NAMESPACE
    15. class Qtimer_thread : public QWidget
    16. {
    17. Q_OBJECT
    18. public:
    19. Qtimer_thread(QWidget *parent = nullptr);
    20. ~Qtimer_thread();
    21. protected slots:
    22. void thread();
    23. void creat_thread();
    24. protected:
    25. void closeEvent(QCloseEvent *event);
    26. private:
    27. QPushButton *btn = nullptr;
    28. QTimer *tim = nullptr;
    29. Ui::Qtimer_thread *ui;
    30. int thread_exit;
    31. };
    32. #endif // QTIMER_THREAD_H