Domanda

I am implementing a simple function where slider value is constantly displayed on label and qDebug(). I already got the label updated using signal/slots, but somehow the qDebug() thread is not working properly. I expected to see the console flooded with the value of the slider. Below is my code: SliderThread.h:

class HorizontalSliderThread : public QThread {
    Q_OBJECT
public:
    HorizontalSliderThread(Ui::MainWindow *ui);//in order to call slider value in HorizontalSliderThread class
    ~HorizontalSliderThread();
public slots:
    void process();
private:
};

SliderThread.cpp

HorizontalSliderThread::HorizontalSliderThread(Ui::MainWindow *ui){
    ui_global = *ui;
}
void HorizontalSliderThread::process(){
    qDebug("Test Thread");
    int value = ui_global.horizontalSlider_windowSize->value();
QObject::connect(ui_global.horizontalSlider_windowSize,SIGNAL(valueChanged(int)),ui_global.label_SliderWindowSize,SLOT(setNum(int)));//update value to label
        qDebug()<<value;    //update value in console

}

mainwindow.h move Ui::MainWindow *ui; from private to public.

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QThread* thread = new QThread;
    HorizontalSliderThread* slider = new HorizontalSliderThread(ui);
    slider->moveToThread(thread);
    connect(thread, SIGNAL(started()), slider, SLOT(process()));
    thread->start();
}

Current Output: qDebug() displays the value of slider once, label is updated constantly.
Expected Output: qDebug() displays the value of slider continuously, label is updated constantly.

Since label is updated when the slider is moved, then the signal/slot for this function is working, which means my thread should be working. Don't know what I'm doing wrong.

QThread implementation is reference from: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

I am fairly new to this, especially QThread, so if there is a better way to implement this function, please let me know!

Thanks a lot.

EDIT1: add slider->moveToThread(thread);

È stato utile?

Soluzione

Well you've only connected the started() signal to your process() function, so your thread starts and it calls process, which dutifully shows your debug output and returns.

I suspect you want to call your process function every time the value changes, which would require another signal/slot connection (along these lines):

connect(ui_global.horizontalSlider_windowSize, SIGNAL(valueChanged(int)), thread, SLOT(setNum(int)));

Also, it looks like you intend for your HorizontalSliderThread to actually run in that separate thread you've created, in which case you'll need a call to QObject::moveToThread() in there, something along these lines:

slider->moveTothread(thread);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top