我有一个worker类,它在无限循环中从ncurses收集输入,并在按下键时发出信号。工作人员附在指南中提到的QThread
。这样可以正常工作,但信号永远不会被插槽捕获。
标题文件:
#ifndef INPUT_H
#define INPUT_H
#include <QObject>
#include <QThread>
class InputWorker : public QObject {
Q_OBJECT
public:
InputWorker();
~InputWorker();
protected:
bool running = true;
public slots:
void run();
void quit();
signals:
void key(char ch);
};
class Input : public QObject {
Q_OBJECT
public:
Input();
public slots:
void key(char ch);
};
#endif // INPUT_H
源文件:
#include "input.h"
#include "ncurses.h"
#include <QDebug>
InputWorker::InputWorker() {
}
InputWorker::~InputWorker() {
}
void InputWorker::run() {
while (this->running) {
char ch = getch();
emit this->key(ch);
thread()->sleep(0.3);
}
}
void InputWorker::quit() {
this->running = false;
}
Input::Input() : QObject() {
InputWorker *w = new InputWorker();
QThread *thread = new QThread();
w->moveToThread(thread);
connect(thread, SIGNAL(started()), w, SLOT(run()));
connect(thread, SIGNAL(finished()), w, SLOT(quit()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(w, SIGNAL(key(char)), this, SLOT(key(char)));
thread->start();
}
void Input::key(char ch) {
qDebug() << ch; // never happens
}