From a30723c3d4f1e017d4ec4847234e13030ef7c17d Mon Sep 17 00:00:00 2001 From: Thomas Harte Date: Sun, 31 May 2020 23:58:19 -0400 Subject: [PATCH] Cleans up a little and ensures a safe exit of the timer thread. --- OSBindings/Qt/mainwindow.cpp | 39 ++++++++++++++++++++++-------------- OSBindings/Qt/mainwindow.h | 6 +++++- 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/OSBindings/Qt/mainwindow.cpp b/OSBindings/Qt/mainwindow.cpp index 5da0b48bd..a70779733 100644 --- a/OSBindings/Qt/mainwindow.cpp +++ b/OSBindings/Qt/mainwindow.cpp @@ -5,8 +5,6 @@ #include "ui_mainwindow.h" #include "timer.h" -Timer *t; - MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) @@ -14,16 +12,23 @@ MainWindow::MainWindow(QWidget *parent) ui->setupUi(this); createActions(); - // Start the emulation timer. TODO: not now. - timer = std::make_unique(this); - QThread *thread = new QThread(this); - timer->setInterval(1); - t = new Timer; - t->moveToThread(thread); - connect(timer.get(), SIGNAL(timeout()), t, SLOT(tick())); - connect(thread, SIGNAL(finished()), t, SLOT(deleteLater())); - thread->start(); - timer->start(); + // Set up the emulation timer. Bluffer's guide: the QTimer will post an + // event to an event loop. QThread is a thread with an event loop. + // My class, Timer, will be wired up to receive the QTimer's events. + qTimer = std::make_unique(this); + qTimer->setInterval(1); + + timerThread = std::make_unique(this); + + timer = std::make_unique(); + timer->moveToThread(timerThread.get()); + + connect(qTimer.get(), SIGNAL(timeout()), timer.get(), SLOT(tick())); + + // Start the thread and timer. + // TODO: not until there's actually something to display. + timerThread->start(); + qTimer->start(); } void MainWindow::createActions() { @@ -47,11 +52,15 @@ void MainWindow::createActions() { void MainWindow::open() { QString fileName = QFileDialog::getOpenFileName(this); -// if(!fileName.isEmpty()) -// loadFile(fileName); + if(!fileName.isEmpty()) { + qDebug() << "Should open" << fileName; + } } MainWindow::~MainWindow() { - // TODO: stop thread somehow? + // Stop the timer by asking its QThread to exit and + // waiting for it to do so. + timerThread->exit(); + while(timerThread->isRunning()); } diff --git a/OSBindings/Qt/mainwindow.h b/OSBindings/Qt/mainwindow.h index a4d8c2b5c..4e21a1055 100644 --- a/OSBindings/Qt/mainwindow.h +++ b/OSBindings/Qt/mainwindow.h @@ -3,6 +3,7 @@ #include #include +#include "timer.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } @@ -19,7 +20,10 @@ class MainWindow : public QMainWindow { private: std::unique_ptr ui; - std::unique_ptr timer; + std::unique_ptr qTimer; + std::unique_ptr timerThread; + std::unique_ptr timer; + private slots: void open();