Passing paramaters from Qt to QML via signal
I've got a project were the UI is designed and written in QML and the backend logic is written in C++ with Qt. What we want to do is using the well known signal-slot concept to pass some data between our C++ backend and the QML UI. I read many tutorials and webpages on how to share data between QML and Qt but I did not find any solution to my problem:
I want to emit a signal in Qt. This signal has got a parameter and this parameter has to be passed to the QML Userinterface. I already figured out how to catch the signal in QML but was not able to receive any paramters passed.
What I did so far is this:
We defined an object to pass and receive signals/slots between QML and Qt
class QMLInterface : public QObject
signals: void fileSelected(QString);
public slots: void selectFile(); ...
The function void QMLInterface::selectFile() is called and the idea is, that it emits the signal fileSelected(filename):
qDebug() << "selecting package file";
filename = QFileDialog::getOpenFileName(view, tr("Open Package"),
The QML Userinterface is able to receive the signal put I've got no idea how to process the paramters:
onFileSelected: test = 'no idea how to process any paramters...'
So maybe anybody got some idea how to receive paramters from Qt? (Is it even possible to this the way we thought about it?)
When declaring the signal, you have to specify parameter names, e.g, instead of:
It should be:
void fileSelected(QString fileName);@
And then in QML, you access the passed parameter with this name, e.g:
onFileSelected: print('Selected file name: ' + fileName)
Hope it helps.
Thank you! This works perfectly!
I'd never thought of specifing the variable in the signal signature.
sorry for bringing this thread again to life but I didn't want to make a duplicate thread.
I understand the above, but if I want to call a method of QString fileName inside qml,
what should I do?
print(fileName.someMethod()) //this one fails,its undefined
I suppose, you need to declare it Q_INVOKABLE, look there: http://qt-project.org/doc/qt-4.8/qtbinding.html#calling-functions
I don't understand the question. fileName is of type QString (or rather, the QML equivalent of it), so it obviously doesn't have the .someMethod() method defined. What do you want to achieve?
By the way, perhaps you should considder making fileName a property of your QMLInterface class (and of course emitting the signal as the NOTIFY signal of that property). That would allow you to simply bind to the property in QML, instead of using an explicit method. Much more in line with declarative programming.
to call a method of qobject from qml you have to define this like a public slot:
then it is callable.
Either a slot, or mark it as Q_INVOKABLE.