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-inherited-member-function
Jump to navigation
Jump to search
[toc align_right="yes" depth="3"]
To call an inherited member function of an object using QtConcurrent::run, you must cast the member function address to the subclass type.
form.h
<br />#ifndef FORM_H<br />#define FORM_H
#include "ui_form.h&quot;
#include "MyClass.h&quot;
class Form : public QWidget, private Ui::Form<br />{<br />Q_OBJECT
public slots:
void slot_finished();<br /> void on_pushButton_clicked();
public:<br /> Form(QWidget *parent = 0);
private:<br /> ChildClass MyObject;
};
#endif
form.cpp
<br />#include <QtGui&gt;<br />#include <QImage&gt;
#include "form.h&quot;<br />#include "MyClass.h&quot;
#include <iostream&gt;
Form::Form(QWidget '''parent)<br /> : QWidget(parent)<br />{<br /> setupUi(this);<br />}
<br />void Form::on_pushButton_clicked()<br />{<br /> QFuture&lt;void&gt; future = QtConcurrent::run(&this->MyObject, static_cast&lt;void(ChildClass::''')()>(&ChildClass::LongFunction));// works<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;
MyClass.h
<br />#ifndef MyClass_H<br />#define MyClass_H
#include <iostream&gt;
class ParentClass<br />{<br />public:
virtual void LongFunction()<br /> {<br /> for( int count = 0; count < 5; count++ )<br /> {<br /> sleep( 1 );<br /> std::cout << "Ping long!" << std::endl;<br /> }<br /> }<br />};
class ChildClass : public ParentClass<br />{<br />public:
void LongFunction()<br /> {<br /> for( int count = 0; count < 5; count++ )<br /> {<br /> sleep( 1 );<br /> std::cout << "Ping long!" << std::endl;<br /> }<br /> }<br />};
#endif
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;);
}