QtConcurrent-run-inherited-member-function: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(clean-up)
Line 40: Line 40:
#include <iostream>
#include <iostream>


Form::Form(QWidget '''parent)
Form::Form(QWidget *parent)
  : QWidget(parent)
  : QWidget(parent)
{
{

Revision as of 11:52, 24 March 2016

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

#ifndef FORM_H
#define FORM_H

#include "ui_form.h"
#include "MyClass.h"

class Form : public QWidget, private Ui::Form
{
Q_OBJECT

public slots:
 void slot_finished();
 void on_pushButton_clicked();

public:
 Form(QWidget *parent = 0);

private:
 ChildClass MyObject;
};

#endif

form.cpp

#include <QtGui>
#include <QImage>

#include "form.h"
#include "MyClass.h"

#include <iostream>

Form::Form(QWidget *parent)
 : QWidget(parent)
{
 setupUi(this);
}

void Form::on_pushButton_clicked()
{
 QFuture<void> future = QtConcurrent::run(&this->MyObject, static_cast<void(ChildClass::*)()>(&ChildClass::LongFunction));
}

form.ui

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

MyClass.h

#ifndef MyClass_H
#define MyClass_H

#include <iostream>

class ParentClass
{
public:
 virtual void LongFunction() {
  for( int count = 0; count < 5; count++ ) {
   sleep( 1 );
   std::cout << "Ping long!" << std::endl;
  }
 }
};

class ChildClass : public ParentClass
{
public:
 void LongFunction() {
  for( int count = 0; count < 5; count++ ) {
   sleep( 1 );
   std::cout << "Ping long!" << std::endl;
  }
 }
};

#endif

main.cpp

  1. include <QApplication>
  2. include <QObject>
  3. include <QThread>
  4. include <iostream>
  1. include "form.h"

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

QApplication app(argc, argv);
Form form;
form.show();
return app.exec();

}