如何从QML ComboBox组件公开属性?

问题描述

我正在制作一个基于ComboBox的组件。

import QtQuick 2.12
import QtQuick.Controls 2.12

ComboBox {
   id: _ComboBox
   property alias textInBox: _delegateText.text

   delegate: ItemDelegate {
        contentItem: Text {
        id: _delegateText
        text: name
        }
   }
}

当我添加一行时: property alias textInBox: _delegateText.text,我没有启动程序就终止了程序。

enter image description here

告诉我如何从外部设置text属性

解决方法

属性contentItemComponent,因此无论放置在哪里,就像在一个单独的文件中定义一样。

定义组件类似于定义QML文档。 QML 文档只有一个顶级项目,用于定义行为和 该组件的属性,并且无法定义属性或行为 在该顶级商品之外。同样,组件 定义包含一个顶级项目(在上面 示例是矩形),并且无法在此之外定义任何数据 项目,除了id(在上面的示例中是 redSquare)。

https://doc.qt.io/qt-5/qml-qtqml-component.html

Delegate从model获取文本,因此您应该在模型上进行工作,而不是委托实例。在您的代表中,您通常通过modelData属性访问文本,但是可以对其进行自定义。

没有命名角色的模型(例如显示的ListModel 下方)将具有通过modelData角色提供的数据。的 还为只有一个角色的模型提供了modelData角色。在 在这种情况下,modelData角色包含的数据与命名角色相同。

https://doc.qt.io/qt-5/qtquick-modelviewsdata-modelview.html#models

这就是您将文本分配给代表的方式。

 delegate: ItemDelegate {
       contentItem: Text {
          text: modelData
       }
 }

如果要修改它,只需修改model即可创建各种绑定。例如,这将起作用(尽管不建议这样做):

   model: [timer.ctr,timer.ctr * 2]

   Timer {
       id: timer
       repeat: true
       interval: 1000
       running: true

       property int ctr: 0

       onTriggered: ctr++
   }
,

我找到了解决方案。根据组合框中角色的转移,将显示模型中的相应字段。

ExComboBox.qml

import QtQuick 2.12
import QtQuick.Controls 2.12

ComboBox {
   delegate: ItemDelegate {
      contentItem: Text {
         text: model[textRole]
      }
   }
}

您需要从模型中指定textRole: "name"或模型中的其他任何字段,而不是"name"

main.qml

ExComboBox {
   currentIndex: 0
   model: GroupModel { }
   textRole: "name"
}

注意: GroupModel是我从C ++代码获得的模型。