Jump to content

QtConcurrent-run-member-function

From Qt Wiki
Revision as of 14:41, 23 February 2015 by Maintenance script (talk | contribs)


[toc align_right="yes" depth="3"]

You can call a member function of an object using QtConcurrent::run as follows. (Note for an inherited member function, please see QtConcurrent-run-inherited-member-function).

form.h

#ifndef FORM_H<br />#define FORM_H

#include &quot;ui_form.h&amp;quot;

#include &quot;MyClass.h&amp;quot;

class Form : public QWidget, private Ui::Form<br />{<br />Q_OBJECT

public slots:

void on_pushButton_clicked();

public:<br /> Form(QWidget *parent = 0);

private:<br /> MyClass MyObject;

};

#endif

form.cpp

<br />#include &lt;QtGui&amp;gt;<br />#include &lt;QImage&amp;gt;

#include &quot;form.h&amp;quot;

#include &lt;iostream&amp;gt;

Form::Form(QWidget *parent)<br /> : QWidget(parent)<br />{<br /> setupUi(this);

}

void Form::on_pushButton_clicked()<br />{<br /> // Start the computation.<br /> QFuture&amp;lt;void&amp;gt; future = QtConcurrent::run(&amp;this-&gt;MyObject, &amp;MyClass::LongFunction);

}<br />

form.ui


&lt;?xml version="1.0&quot; encoding="UTF-8&quot;?&gt;
<ui version="4.0&quot;>
<class&gt;Form&lt;/class&gt;
<widget class="QWidget&quot; name="Form&quot;>
<property name="geometry&quot;>
<rect&gt;
<x&gt;0&lt;/x&gt;
<y&gt;0&lt;/y&gt;
<width&gt;400&lt;/width&gt;
<height&gt;300&lt;/height&gt;
</rect&gt;
</property&gt;
<property name="windowTitle&quot;>
<string&gt;Form&lt;/string&gt;
</property&gt;
<layout class="QVBoxLayout&quot; name="verticalLayout&quot;>
<item&gt;
<widget class="QPushButton&quot; name="pushButton&quot;>
<property name="text&quot;>
<string&gt;PushButton&lt;/string&gt;
</property&gt;
</widget&gt;
</item&gt;
</layout&gt;
</widget&gt;
<resources/&gt;
<connections/&gt;
</ui&gt;

MyClass.h

<br />#ifndef MyClass_H<br />#define MyClass_H

#include &lt;iostream&amp;gt;

class MyClass<br />{<br />public:

void LongFunction()<br /> {<br /> for( int count = 0; count &lt; 5; count++ )<br /> {<br /> sleep( 1 );<br /> std::cout &lt;&lt; &quot;Ping long!&quot; &lt;&lt; std::endl;<br /> }<br /> }<br />};

#endif<br />

main.cpp


#include <QApplication&gt;
#include <QObject&gt;
#include <QThread&gt;

  1. include <iostream&gt;
  1. include "form.h&quot;

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

Form form;

form.show();

return app.exec&amp;#40;&#41;;