Note that there are some explanatory texts on larger screens.

plurals
  1. POQt threads - new way verification please
    text
    copied!<p>So new to Qt. Read the wiki and C++ Gui programming book and they say subclass QThread. Found that this is not the recommended way now.</p> <p>So I have some practice code here and I have some questions about if this is correct. So I would really appreciate someone having a look please.</p> <p>So I created a class with the QThread as a private member to use for the movetothread. When creating it, I made sure not to specify a parent. Therefore my first question is, is this ok to do?</p> <p>Second question comes from the m_thread->quit(); I found that my connect to finished wasn't being emitted until I did this. So is this the correct way? I read <a href="http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/" rel="nofollow">http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/</a> and saw that the connect between finished and deleteLater in the same thread but not 100% sure if this should be used with quit. </p> <p>Finally, with the talk of deleteLater, does this mean I dont need delete m_thread</p> <p>Thanks for anyones time.</p> <p>Code here. Simple QDialog with a pushbutton. <strong>worker.cpp</strong></p> <pre><code>#include "worker.h" worker::worker(QObject *parent) : QObject(parent) { stopped = false; } void worker::setupAndRun() { m_thread = new QThread(); connect(m_thread,SIGNAL(started()),this,SLOT(doWork())); connect(m_thread,SIGNAL(finished()),this,SLOT(onComplete())); connect(m_thread,SIGNAL(finished()),m_thread,SLOT(deleteLater())); this-&gt;moveToThread(m_thread); m_thread-&gt;start(); } void worker::doWork() { for(int i = 0; i &lt; 20000; i++) { if (this-&gt;stopped) break; qDebug() &lt;&lt; i &lt;&lt; " : " &lt;&lt; Q_FUNC_INFO &lt;&lt; m_thread-&gt;currentThreadId(); } // --- I think the quit calls the finished signal? m_thread-&gt;quit(); } void worker::onComplete() { qDebug() &lt;&lt; Q_FUNC_INFO &lt;&lt; "Called " &lt;&lt; m_thread-&gt;currentThreadId(); } </code></pre> <p><strong>worker.h</strong></p> <pre><code>#ifndef WORKER_H #define WORKER_H #include &lt;QObject&gt; #include &lt;QDebug&gt; #include &lt;QThread&gt; class worker : public QObject { Q_OBJECT public: explicit worker(QObject *parent = 0); void setupAndRun(); signals: public slots: void doWork(); void onComplete(); private: // --- The thread that I use to movetothread with. // Is this ok? QThread *m_thread; bool stopped; }; #endif // WORKER_H </code></pre> <p><strong>Dialog push button</strong></p> <pre><code>void Dialog::on_pushButton_clicked() { m_worker = new worker(); m_worker-&gt;setupAndRun(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload