gpt4 book ai didi

c++ - qml + 主从

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:04:05 30 4
gpt4 key购买 nike

我想将 qml 与主从界面一起使用,但我不知道如何以正确的方式将当前项目传递到详细信息 View 。主视图中的 ListView 使用 C++ 模型(QSQLTableModel 的附加组件,它工作正常),我看到两种传递项目的方法:

  1. 使用静态名称(如 QSqlRecord 字段名称)的字段创建 C++ 类,并使用 w->rootContext()->setContextProperty()(w 是 QDeclarativeView *)将其传递给 qml,但是现在我不使用任何这样的类并且可以在不更改 C++ 代码的情况下更改我的数据库和 qml View ,我想保存它

  2. 在任何细节 qml 中创建很多属性,例如

    Rectangle {
    id: mainRect
    property alias myFieldName: txt_nominal.text
    Column {

    width: parent.width
    Text {
    id: txt_nominal
    font.bold: true
    }
    }
    }

并通过设置 w->rootContext()->setContextProperty(record.fieldName(i),record.field(i).value());(记录- 当前行的 QSqlRecort)

有没有更简单的方法来解决我的问题?

PS 我上面写的代码没有检查准确性,写的是为了更清楚我的意思

UPD

也许它对某些人有用,我发现了第三种方式,而不是第二种方式的修改 - 您可以将字段包装到 QVariantMap 中,并只将一个对象传递给 qml。这正是我想要的

在 cpp 中:

QVariantMap testObject;
testObject["testField"]="first string from cpp";
testObject["testField2"]="second string from cpp";
rootContext()->setContextProperty("testObject",testObject);

在 qml 中:

Text {
id: simpleTextt
text: testObject.testField
anchors.centerIn: parent
}

最佳答案

您可以使用委托(delegate)的 isCurrentItem 属性将数据从 ListView 委托(delegate)传递到您的详细信息 qml。这样你就可以不用添加额外的 C++ 代码就可以摆脱困境。这基本上是您的第二种方法,但没有 c++。您也不需要添加很多属性,只要您要更改的每个 QML 元素都有一个 id

如果您有许多用于不同详细信息 View 的不同 QML,您还必须使用加载器来加载适当的详细信息 QML。

只是一个玩具示例,假设您只有一个用于列表中所有元素的详细信息模板(如上所述,如果不是这种情况,则可以使用加载器而不是 detailsRect):

Rectangle {
width: 300; height: 400

Rectangle {
id: detailsRect
anchors.right: parent.right
width: 100
height: 500
color: "blue"
Text {
id: detailsText
text: ""
}
}

ListView {
id: list
anchors.fill: parent
model: 20

delegate: Rectangle {
color: ListView.isCurrentItem ? "red" : "green"
width: 40
height: 40

Text {
text: index
}

ListView.onIsCurrentItemChanged: {
if(ListView.isCurrentItem)
{
detailsRect.color = "yellow"
detailsText.text = index
}
}

MouseArea {
anchors.fill: parent
onClicked: {
list.currentIndex = index
}
}
}
}
}

关于c++ - qml + 主从,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13641765/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com