[Qt-qml] Custom data type in slot parameter

Robert Voinea rvoinea at gmail.com
Fri Oct 22 08:06:14 CEST 2010


Hi

I have a QtDeclarative application and I want to connect a signal in my C++ 
code to a QML slot.

The problem is that the signal in the C++ code has a custom data type 
(ButtonInformation).
I have registered the custom data type with qRegisterMetaType,
Q_DECLARE_METATYPE (so that it can be used with signals/slots) and with 
qmlRegisterType. 

If I set the parameter's type to QVariant, the slot gets called but I cannot 
see any properties of the parameter.
If I set the parameter's type to ButtonInformation then connect says there is 
no such slot...

Any hits on how to achieve this?

Code follows:

/** Button Information */
class ButtonInformation;
Q_DECLARE_METATYPE(ButtonInformation);

class ButtonInformation : public QObject
{
	Q_OBJECT
public:
	ButtonInformation(QObject* parent = 0);
	ButtonInformation(const ButtonInformation& b);
	virtual ~ButtonInformation();

	Q_PROPERTY(QString text READ text WRITE setText);
	QString text() const;
	void setText(const QString& s);
private:
	QString m_text;
};

/** MainView.h */
class MainView : public QDeclarativeView
{
	Q_OBJECT
public:
	explicit MainView(QWidget* parent = 0);
	virtual ~MainView();
	void doSomething();
signals:
	// void buttonAdd(ButtonInformation b);
	void buttonAdd(QVariant b);
};

/** MainView.cpp */
void MainView::doSomething()
{
	ButtonInformation b;
	b.setText("The Text");
	// emit buttonAdd(v);

	QVariant v;
	v.setValue(b);
	emit buttonAdd(v);
}

MainView::MainView(QWidget* parent) : QDeclarativeView(parent)
{
	setSource("main.qml");

	QObject* obj = rootObject();
	if (!obj)
		::exit(1);

	// connect(this, SIGNAL(buttonAdd(ButtonInformation)), obj, 
	// 	SLOT(buttonAdd(ButtonInformation)));
	connect(this, SIGNAL(buttonAdd(QVariant)), obj, 
		SLOT(buttonAdd(QVariant)));
	show();
}

/** main.cpp */
int main(int argc, char** argv)
{
	QApplication app(argc, argv);

	qmlRegisterType<ButtonInformation>("btn", 1, 0, "ButtonInformation");
	qRegisterMetaType<ButtonInformation>("ButtonInformation");

	MainView view;
	view.show();
	return app.exec();
}

/** main.qml */
import Qt 4.7
import btn 1.0
Rectangle
{
	id: main;
	property alias text: txt.text;

	Text
	{
		id: txt;
		text: "Default text";
	}
	function buttonAdd(ButtonInformation b)
	{
		main.text = b.text;
	}
}
-- 
Robert Voinea
IT Specialist
+4 0740 467 262
rvoinea (at) gmail [dot] com 



More information about the Qt-qml mailing list