1、在与qml通信的时候,需要把函数接口暴露给qml需要在函数前面加入Q_INVOKABLE关键字,且需要注意成员函数的公有或私有类型。
例如:
.h文件
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); Q_INVOKABLE QString sendData(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
.cpp文件
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QQuickItem> #include <QQmlApplicationEngine> #include <QQuickView> #include <QQmlContext> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QUrl soucre("qrc:/qml/text.qml"); ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView); ui->quickWidget->rootContext()->setContextProperty("testData", this); ui->quickWidget->setSource(soucre); ui->quickWidget->setClearColor(QColor(Qt::transparent)); } MainWindow::~MainWindow() { delete ui; } QString MainWindow::sendData() { QString str = "blue"; return str; }
main.cpp
#include "mainwindow.h" #include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QQuickView> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
text.qml
import QtQuick 2.0 import QtQuick.Controls 1.4 Rectangle{ id:root; height:200; width:200; color: "red" Text { anchors.centerIn: parent text: qsTr("hello") } MouseArea{ anchors.fill: parent; onClicked: { root.color = testData.sendData() } } }