15

I have a Qt function:

void MainWindow::button_clicked(Qstring a, Qstring b, Qstring c, Qstring d)

I collect data from QML and I want to pass data to this function which is in Qt. So I know I need to use Q_INVOKABLE but don't know really how to use it.

And one more thing is it possible to invoke some other function when invoke this certain above.
For example: I invoke the above function but in her body I invoke refresh() function. Is this possible?

ymoreau
  • 3,402
  • 1
  • 22
  • 60
user123_456
  • 5,635
  • 26
  • 84
  • 140

1 Answers1

26

To be able to call a method from QML, you must either mark it with Q_INVOKABLE or as a slot. I prefer Q_INVOKABLE if it's not meant to be used as a slot, as its more minimal.

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
...
    Q_INVOKABLE void buttonClicked( const QString& a, const QString& b, const QString& c, const QString& d );
....
};

void MainWindow::buttonClicked( const QString& a, const QString& b, const QString& c, const QString& d ) {
   ...do stuff
   update(); //example
}

The implementation of buttonClicked() can contain any C++ code.

To make the main window instance accessible from QML, you must register it, e.g.

QDeclarativeView* view = ...your view
view->rootContext()->setContextProperty( "_mainWindow", mainWindow );

Once registered, you can call buttonClicked from QML:

_mainWindow.buttonClicked("foo", "bar", "c", "d")
Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70
  • hi I have this in mainwindow.cpp : `QDeclarativeView *view= new QDeclarativeView; ui->setupUi(this); setCentralWidget(view); QDeclarativeContext *ctxt = view->rootContext(); ctxt->setContextProperty("myModel", QVariant::fromValue(MainWindow::dataList)); view->setSource(QUrl("qrc:/gui.qml")); view->setResizeMode(QDeclarativeView::SizeRootObjectToView);` so how to put your line inside? In main.cpp I only create mainwindow and call show method. – user123_456 Feb 18 '12 at 15:39
  • It probably would be ctxt->setContextProperty( "_mainWindow", this ); then. – Frank Osterfeld Feb 18 '12 at 17:40
  • Akiva: With "registering" I meant setting it as context property on the root context, as done in the snippet that follows above. – Frank Osterfeld Sep 25 '14 at 05:55