Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Created June 25, 2014 06:33
Show Gist options
  • Save ochinchina/59d121462bcfd6f71ba6 to your computer and use it in GitHub Desktop.
Save ochinchina/59d121462bcfd6f71ba6 to your computer and use it in GitHub Desktop.
Demo the QT dynamic invokes
#include "dynamicinvoke.h"
#include <QDebug>
TestObject::TestObject( const char* _str )
{
this->str = _str;
}
DynamicInvoke::DynamicInvoke( QObject* parent )
:QObject( parent ){
}
DynamicInvoke::~DynamicInvoke() {
}
void DynamicInvoke::doInvoke() {
//before dynamic calling, call qRegisterMetaType method
qRegisterMetaType<TestObject*>();
TestObject* pObj = new TestObject( "hello");
QMetaObject::invokeMethod( this, "printString", Q_ARG( TestObject*, pObj) );
}
void DynamicInvoke::printString( TestObject* testObj ) {
qDebug() << testObj->str;
testObj->deleteLater();
}
#ifndef DYNAMICINVOKE_H
#define DYNAMICINVOKE_H
#include <QObject>
#include <QPointer>
class TestObject: public QObject
{
Q_OBJECT
public:
TestObject( const char* str );
QString str;
};
class DynamicInvoke: public QObject
{
Q_OBJECT
public:
DynamicInvoke( QObject* parent = 0 );
~DynamicInvoke();
void doInvoke();
private slots:
void printString( TestObject* );
};
//declare the TestObject as MetaType
Q_DECLARE_METATYPE( TestObject* )
#endif // DYNAMICINVOKE_H
Copy all the files in this project to your QT creator, rebuild and run it.
#include <QCoreApplication>
#include <QThread>
#include "dynamicinvoke.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
DynamicInvoke dInvoke;
QThread thread;
dInvoke.moveToThread( &thread );
thread.start();
dInvoke.doInvoke();
return a.exec();
}
#-------------------------------------------------
#
# Project created by QtCreator 2014-06-24T03:02:08
#
#-------------------------------------------------
QT += core
QT -= gui
TARGET = QtDynamicInvokeTest
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
dynamicinvoke.cpp
HEADERS += \
dynamicinvoke.h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment