Difference between revisions of "QtConcurrent-run-member-function"

From Qt Wiki
Jump to: navigation, search
(Add "cleanup" tag)
Line 1: Line 1:
 +
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
 +
 
[[Category:snippets]]
 
[[Category:snippets]]
 
[toc align_right="yes" depth="3"]
 
[toc align_right="yes" depth="3"]

Revision as of 16:38, 3 March 2015

[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

  1. define FORM_H
  1. include "ui_form.h"
  1. include "MyClass.h"

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

public slots:

void on_pushButton_clicked();

public:

Form(QWidget *parent = 0);

private:

MyClass MyObject;

};

  1. endif

form.cpp

  1. include <QtGui>
  2. include <QImage>
  1. include "form.h"
  1. include <iostream>

Form::Form(QWidget *parent)

: QWidget(parent)

{

setupUi(this);

}

void Form::on_pushButton_clicked() {

// Start the computation.
QFuture<void> future = QtConcurrent::run(&this->MyObject, &MyClass::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

  1. ifndef MyClass_H
  2. define MyClass_H
  1. include <iostream>

class MyClass { public:

void LongFunction()

{
for( int count = 0; count < 5; count++ )
{
sleep( 1 );
std::cout << "Ping long!" << std::endl;
}
}

};

  1. endif

main.cpp

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

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

QApplication app(argc, argv);

Form form;

form.show();

return app.exec();