Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.
QtConcurrent-run-free-function
Jump to navigation
Jump to search
[toc align_right="yes" depth="3"]
To call a free function using QtConcurrent::run, simply pass the function name.
form.h
<br />#ifndef FORM_H<br />#define FORM_H
#include "ui_form.h&quot;
class Form : public QWidget, private Ui::Form<br />{<br />Q_OBJECT
public slots:
void on_btnOpen_clicked();
public:<br /> Form(QWidget *parent = 0);
};
#endif
form.cpp
<br />#include <QtGui&gt;<br />#include <QImage&gt;
#include "form.h&quot;
#include <iostream&gt;
Form::Form(QWidget *parent)<br /> : QWidget(parent)<br />{<br /> setupUi(this);<br />}
void LongFunction()<br />{<br /> for( int count = 0; count < 5; count++ )<br /> {<br /> sleep( 1 );<br /> std::cout << "Ping long!" << std::endl;<br /> }<br />}
void Form::on_btnOpen_clicked()<br />{<br /> QFuture&lt;void&gt; result = QtConcurrent::run ( LongFunction );<br /> //result.waitForFinished();
std::cout << "exit." << std::endl;<br />}
form.ui
<br />&lt;?xml version="1.0&quot; encoding="UTF-8&quot;?&gt;<br /><ui version="4.0&quot;><br /> <class&gt;Form&lt;/class&gt;<br /> <widget class="QWidget&quot; name="Form&quot;><br /> <property name="geometry&quot;><br /> <rect&gt;<br /> <x&gt;0&lt;/x&gt;<br /> <y&gt;0&lt;/y&gt;<br /> <width&gt;400&lt;/width&gt;<br /> <height&gt;300&lt;/height&gt;<br /> </rect&gt;<br /> </property&gt;<br /> <property name="windowTitle&quot;><br /> <string&gt;Form&lt;/string&gt;<br /> </property&gt;<br /> <layout class="QVBoxLayout&quot; name="verticalLayout&quot;><br /> <item&gt;<br /> <widget class="QPushButton&quot; name="pushButton&quot;><br /> <property name="text&quot;><br /> <string&gt;PushButton&lt;/string&gt;<br /> </property&gt;<br /> </widget&gt;<br /> </item&gt;<br /> </layout&gt;<br /> </widget&gt;<br /> <resources/&gt;<br /> <connections/&gt;<br /></ui&gt;
main.cpp
#include <QApplication>
#include <QObject>
#include <QThread>
- include <iostream>
- include "form.h"
int main(int argc, char*argv[])
{
QApplication app(argc, argv);
Form form;
form.show();
return app.exec&#40;);
}