为了能够从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& d ) {
...do stuff
update(); //example
}
buttonClicked()的实现可以包含任何C代码.
要使主窗口实例可从QML访问,您必须注册,例如
QDeclarativeView* view = ...your view
view->rootContext()->setContextProperty( "_mainWindow",mainWindow );
注册后,您可以从QML调用buttonClicked
_mainWindow.buttonClicked("foo","bar","c","d")