我正在尝试创建一个在我的 Singleton 工作线程中每 n 秒触发一次的事件。信号/槽连接(信号是 QTimer 超时,槽是调用另一个 Singleton 类的 lambda 函数)无法正常工作。连接调用成功,计时器处于活动状态,并且我在控制台上没有收到 QTimer 投诉。如果我尝试打印 QTimer 的剩余时间,它会显示 -1。对于我的一生,我无法弄清楚为什么“超时”永远不会被打印(表明事件正在被触发)。任何帮助将不胜感激。为了简单起见,我们可以假设 OtherSingleton 具有相同的结构。我还应该注意到这个 Singleton 类对象是在 QThread 内部运行的。
单例.h:
#include <QObject>
#include <string>
#include <QTimer>
#include <QThread>
class Singleton : public QObject
{
Q_OBJECT
public:
static Singleton& get_instance();
Singleton(Singleton const&) = delete;
void operator=(Singleton const&) = delete;
static void stop_client();
static void start_client();
private:
Singleton();
static QTimer bytes_timer_;
};
单例.cpp:
#include "Singleton.h"
#include <QDebug>
#include <QTime>
#include <QFile>
Singleton::Singleton()
{
bytes_timer_.setParent(this);
bytes_timer_.moveToThread(QThread::currentThread());
bytes_timer_.setInterval(1000);
qDebug() << "Timeout success:" << connect(&bytes_timer_, &QTimer::timeout, this, [&]() {
qDebug() << "timeout";
// . . .
}, Qt::DirectConnection);
}
Singleton& Singleton::get_instance() {
static Singleton instance;
return instance;
}
void Singleton::start_client() {
bytes_timer_.start();
}
void Singleton::stop_client() {
bytes_timer_.stop();
}
QTimer Singleton::bytes_timer_;
主窗口.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include "singleton.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
QThread thread;
Singleton *s;
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
主窗口.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
s = &Singleton::get_instance();
s->moveToThread(&thread);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
thread.start();
s->start_client();
}
主要.cpp:
#include "mainwindow.h"
#include <QApplication>
#include <QThread>
#include "singleton.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}