使用 Q_INVOKABLE 将 C++ 与 QML 连接起来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9341005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:41:48  来源:igfitidea点击:

Connecting C++ with QML using Q_INVOKABLE

c++qtqmlqt-slot

提问by user123_456

I have a Qt function:

我有一个 Qt 函数:

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_INVOKABLEbut don't know really how to use it.

我从 QML 收集数据,我想将数据传递给 Qt 中的这个函数。所以我知道我需要使用Q_INVOKABLE但不知道如何使用它。

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?

还有一件事是在调用上面的某个函数时可以调用其他一些函数。
例如:我调用了上面的函数,但在她的身体中我调用了refresh()函数。这可能吗?

回答by Frank Osterfeld

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.

为了能够从 QML 调用方法,您必须使用 Q_INVOKABLE 或作为槽标记它。如果不打算用作插槽,我更喜欢 Q_INVOKABLE,因为它更小。

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.

buttonClicked() 的实现可以包含任何 C++ 代码。

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

要从 QML 访问主窗口实例,您必须注册它,例如

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

Once registered, you can call buttonClicked from QML:

注册后,您可以从 QML 调用 buttonClicked:

_mainWindow.buttonClicked("foo", "bar", "c", "d")