当我从QObject向MainWindow发出信号时,为什么MainThread没有抓住它,我在使用Ubuntu 16.04 有时它会捕获,但只发生一次,然后线程继续在事件循环中运行, 我只是想完成线程,如果有一些工作完成,然后我必须重复使用....
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
class newiDeviceDetect *deviceDetect;
private:
Ui::MainWindow *ui;
public slots:
void on_deviceDetected();
};
class newiDeviceDetect : public QObject
{
Q_OBJECT
public:
explicit newiDeviceDetect(QObject *parent = 0);
QThread *newDeviceThread;
signals:
void killMe();
public slots:
void threadWorker();
};
MainWindow *mainClass;
static void usbHotPlugDetectHand(int sig)
{
qDebug() << "GOT SIGNAL" + QString::number(sig);
emit mainClass->usbHotPlugDetect();
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mainClass = this;
deviceDetect = new newiDeviceDetect;
connect(deviceDetect,SIGNAL(killMe()),this,SLOT(on_deviceDetected()));
signal(SIGUSR1,usbHotPlugDetectHand);
connect(this,SIGNAL(usbHotPlugDetect()),this,SLOT(on_usbHotPlugDetect()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_usbHotPlugDetect()
{
deviceDetect->threadLock.lock();
deviceDetect->newDeviceThread->start();
}
void MainWindow::on_deviceDetected()
{
deviceDetect->newDeviceThread->terminate();
deviceDetect->newDeviceThread->wait();
deviceDetect->threadLock.unlock();
}
newiDeviceDetect::newiDeviceDetect(QObject *parent) : QObject(parent)
{
newDeviceThread = new QThread;
connect(newDeviceThread,SIGNAL(started()),this,SLOT(threadWorker()));
moveToThread(newDeviceThread);
//Some Work
}
void newiDeviceDetect::threadWorker()
{
sleep(5);
//Some Work
killMe();
}
在我的代码中threadWorker工作正常,但当它向killWindow发出killMe信号时,MainWindow Class doest捕获它,我必须完成/终止newDeviceThread再次使用它
感谢任何帮助,谢谢你
答案 0 :(得分:0)
你需要为你创建的每个新线程连接信号,看起来你只做了一次,你的代码对我来说有点混乱。
我的意思是
之后newDeviceThread = new QThread;
connect(newDeviceThread,SIGNAL(started()),this,SLOT(threadWorker()));
你还需要连接到终止你的工作线程的插槽,在你看来我认为是MainWindow::on_deviceDetected()
?
这究竟应该做什么? class
创建了一个新课程,在这种情况下可能不是您想要的......
class newiDeviceDetect *deviceDetect;