jeudi 26 janvier 2017

why QMainWindow not catching signal from QThread

When I emit signal to MainWindow from QObject which is running in different thread why MainThread doesn't catch it sometime it catch but that only happen once after that the thread continues to run in event loop, i just want to finish the thread if some work is done and after then i have to reuse it....

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();
}

Aucun commentaire:

Enregistrer un commentaire