Q:

Qt crashes/doesn't appear when i use Qthread::sleep to update progress bar

I am kinda new to QT so i am wondering why is this invalid:
I have a progress bar and i want to update it by using a class that inherits QThread. 
void mt::run(QProgressBar * asd){

for(int i = 0;i<100;i++){
    asd->setValue(i);
    QThread::sleep(100);
}

}

mt is a class that inherits QThread.  run is overloaded with a QProgressBar argument.  My main UI thread will send it's progressbar like this m.run(ui->progressBar);.  If i will remove the QThread::sleep(100); then it will work fine but i won't be able to see the increment because the thread will be done so fast.  But if i will put a little delay, my screen won't appear at all. 

A:

You can access and update GUI elements from the main thread only. 
If you want to prepare some data inside a custom thread, you should use the signals/slots mechanism to send that data to your widgets. 
Here's a basic example:
class MyThread : public QThread
{
    Q_OBJECT
public:
    MyThread(QObject *parent = 0);

signals:
    void valueChanged(int value);

protected:
    void run();
}

void MyThread::run()
{
    for (int i = 0; i < 100; i++)
    {
        emit valueChanged(i);
        QThread::sleep(100);
    }
}

MyWidget::MyWidget(QWidget *parent) : 
    QWidget(parent)
{
    QHbovLayout *layout = new QHbovLayout(this);
    QProgressBar *pb = new QProgressBar;
    layout->addWidget(pb);

    MyThread *t = new MyThread(this);
    connect(t, SIGNAL(valueChanged(int)), pb, SLOT(setValue(int)));

    t->start();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // we are in the main thread here, so we can create a widget
    MyWidget w;
    w.show();

    return a.exec();
}

