C++对象与QML属性

导出

//QQuickView

QQuickview viewer;
viewer.rootContext()-> setContextProperty("colorMaker",new ColorMaker);
viewer.serSource(QUrl("qrc:///main.qml"));

从堆上分配了一个ColorMaker对象,然后注册为QML上下文是属性,名字为colorMaker。
viewer.rootContext()返回的是QQmlContext对象。QQmlContext类代表一个QML上下文,它的setContextProperty()方法可以为该上下文设置一个全局可见的属性。

QQmlApplicationEngine+Window

QQmlApplicationEngine engine;
engine.rootContext()-> setContextProperty("colorMaker",new ColorMaker);

engine.load(QUrl(QStringLiteral("qrc:///main.qml")))

在一个qml文件中:


Window {
    objectName: "rootObject"
    visible: true
    width: 360
    height: 360
    title: qsTr("Hello World")
    Text{
        objectName: "textLabel";
        text:"hello world"
        anchors.centerIn: parent
        font.pixelSize: 26
    }
    Button{
        anchors.right:parent.right
        anchors.rightMargin: 4;
        anchors.bottom: parent.bottom;
        anchors.bottomMargin: 4;
        text:"quit"
        objectName: "quitButton"
    }
}

在cpp文件中可以这样使用:

QList<QObject *>rootObjects=engine.rootObjects();
qDebug()<<rootObjects;
//QQuickWindowQmlImpl(0x7f80xxxx,name="rootObject")
//遍历rootOject的子对象
int count=rootObjects.size();
for(int i=0;i<count;i++){
    if(rootObjects.at(i)->objectName()=="rootObject"){
        root=rootObjects.at(i);
        break;
    }
}
new ChangeQmlColor(root);
QObject *quitbutton=root->findChild<QObject *>("quitButton");


QObject *textLabel=root->findChild<QObject *>("textLabel");
bool bRet=QMetaObject::invokeMethod(textLabel,"setText",Q_ARG(QString,"world hello"));
qDebug()<<"call setText return "<<bRet;

textLabel->setProperty("color"QColor::fromRgb(255,0,0));
bRet=QMeatObject::invokeMethod(textLAbel,"doLayout");
qDebug()<<"call dolayout return "<<bRet;

上述通过textLabel找到了textLabel对象,使用invokeMEthod()调用setText()方法来改变textLabel的文本,这个注定失败;因为QML中Text对象对应着C++的QQuickText类,而QQuickText没有名为“setText”的槽或者可调用方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值