Skip to content

Instantly share code, notes, and snippets.

@candycode
Created November 13, 2012 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save candycode/4064669 to your computer and use it in GitHub Desktop.
Save candycode/4064669 to your computer and use it in GitHub Desktop.
Invoke QObject constructor at run-time
#include <iostream>
#include <QString>
#include <QMetaObject>
#include <QMetaType>
#include <QObject>
#include <QMetaMethod>
#include "TestObject.h"
int main( int , char** ) {
const QMetaObject* mo = &TestObject::staticMetaObject;
TestObject* to = qobject_cast< TestObject* >( mo->newInstance( Q_ARG( QString, "constructed!" ), Q_ARG( QObject*, 0 ) ) ) ;
std::cout << qPrintable( to->getText() ) << std::endl;
return 0;
}
// use with qmetaobject-newinstance.cpp
#include <iostream>
#include <QObject>
#include <QString>
#include <QVariantMap>
#include <QVariantList>
#include <QList>
#include <QVector>
class TestObject : public QObject {
Q_OBJECT
public:
Q_INVOKABLE TestObject( QObject* parent = 0 ) : QObject( parent ) {}
Q_INVOKABLE TestObject( const QString& astring, QObject* parent ) : QObject( parent ), text_( astring ) {}
Q_INVOKABLE TestObject( const TestObject& other ) : text_( other.text_ ) {}
public slots:
const QString& getText() const { return text_; }
void method( const QString& msg ) {
std::cout << msg.toStdString() << std::endl;
}
void emitSignal( const QString& msg ) {
std::cout << "emitting signal aSignal(" << msg.toStdString() << ")" << std::endl;
emit aSignal( msg );
}
void aSlot( const QString& msg ) {
std::cout << "aSlot() called with data: " << msg.toStdString() << std::endl;
}
QString copyString( const QString& s ) { return s; }
QVariantMap copyVariantMap( const QVariantMap& vm ) { return vm; }
QVariantList copyVariantList( const QVariantList& vl ) { return vl; }
QObject* createObject() {
TestObject* mo = new TestObject;
mo->setObjectName( "New Object" );
return mo; //WARNING: NOT DESTROYED WHEN GARBAGE COLLECTED
//SINCE DEFAULT IS 'QOBJ_NO_DELETE'
}
QList< float > copyFloatList( const QList< float >& l ) { return l; }
QVector< float > copyFloatVector( const QVector< float >& v ) { return v; }
QList< short > copyShortList( const QList< short >& l ) { return l; }
QVector< short > copyShortVector( const QVector< short >& v ) { return v; }
signals:
void aSignal(const QString&);
private:
QString text_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment