qml中QtObject類型的用法小結(jié)
一、描述
QtObject 類型是一個非可視元素,僅包含 objectName 屬性。
如果需要一個非常輕量級的類型來包含一組自定義屬性,那么創(chuàng)建一個 QtObject 會很合適:
import QtQuick 2.0
Item
{
QtObject
{
id: attributes
property string name
property int size
property variant attributes
}
Text { text: attributes.name }
}它對于 C++ 集成也很有用,因為它繼承自 QObject。
二、屬性成員
objectName : string
此屬性保存對象實例的 QObject::objectName。
這允許 C++ 應(yīng)用程序使用 QObject::findChild() 方法在 QML 組件中定位項目。
例如,以下 C++ 應(yīng)用程序定位子 Rectangle 項并動態(tài)更改其顏色值:
// MyRect.qml
import QtQuick 2.0
Item
{
width: 200; height: 200
Rectangle
{
anchors.fill: parent
color: "red"
objectName: "myRect"
}
}// main.cpp
QQuickView view;
view.setSource(QUrl::fromLocalFile("MyRect.qml"));
view.show();
QQuickItem *item = view.rootObject()->findChild<QQuickItem*>("myRect");
if (item)
item->setProperty("color", QColor(Qt::yellow));三、其他
私有化,,,來看以下例子
// MyRectangle .qml
import QtQuick 2.0
import QtQml 2.12
Rectangle {
id: rect
width: 100
height: 100
color: "green"
Component.onCompleted: {
console.log(attributes.usrName)
}
property string hobby: ""
property alias attr: attributes
QtObject {
id: attributes
property string usrName: "zhangSan"
}
}// main.qml
import QtQuick 2.0
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQml 2.12
Window {
visible: true
width: 800
height: 480
title: qsTr("Hello World")
Row {
MyRectangle {
hobby: "play games..."
Component.onCompleted: {
attr.usrName = "zhangSan"
console.log(attr.usrName)
}
}
}
}MyRectangle組件中的 hobby屬性可以直接訪問賦值,例如在main.qml中 MyRectangle{ hobby: “xxx” … }。
但是如何使其不能被訪問 呢???
就可以將其放置在QtObject類型中。例如,MyRectangle.qml中:
QtObject {
id: attributes
property string usrName: "zhangSan"
}此時,在main.qml中就不能直接通過 MyRectangle { usrName: “xxx” }這種形式訪問賦值了,否則報錯如下:
qrc:/main.qml:17 Cannot assign to non-existent property “usrName”
// main.qml
Row {
MyRectangle {
hobby: "play games..."
usrName: "zzzz" // 錯誤,
Component.onCompleted: {
attr.usrName = "zhangSan"
console.log(attr.usrName)
}
}
}起到了一種類似私有化的作用(僅限在MyRectangle.qml中訪問)。
注意:當然,以上私有化也不是絕對的。。
如果確實需要在main.qml中定義的MyRectangle類型中訪問usrName屬性,
可以事先在MyRectangle.qml中對QtObject類型進行別名設(shè)置,例如
property alias attr: attributes
此時,就可以main.qml中訪問了,,,例如
Component.onCompleted: {
attr.usrName = "zhangSan"
console.log(attr.usrName)
}到此這篇關(guān)于qml中QtObject類型的使用的文章就介紹到這了,更多相關(guān)qml QtObject類型內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mac OS上搭建Apache+PHP+MySQL開發(fā)環(huán)境的詳細教程
這篇文章主要介紹了Mac OS上搭建Apache+PHP+MySQL開發(fā)環(huán)境的詳細教程,包括常見的PHP連接MySQL失敗問題的解決辦法,需要的朋友可以參考下2016-01-01
C語言素數(shù)(質(zhì)數(shù))判斷的3種方法舉例
這篇文章主要給大家介紹了關(guān)于C語言素數(shù)(質(zhì)數(shù))判斷的3種方法,質(zhì)數(shù)是只能被1或者自身整除的自然數(shù)(不包括1),稱為質(zhì)數(shù),文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-11-11

