首页 文章

通用QML委托,但非通用的View附加属性?

提问于
浏览
3

视图将属性附加到委托 . 对于ListView,委托可以访问 ListView.view.widthListView.isCurrentItem 属性:

Rectangle {
  width: ListView.view.width
  height: 40

  color: ListView.isCurrentItem ? "gray" : "lightGray"

  Text {
    anchors.centerIn: parent       
    text: index
  }
}

通过按类型名称引用View,似乎Delegate失去了它的通用性 .

如果我想在GridView中使用相同的委托怎么办?

1 回答

  • 2

    您应该从委托中创建一个Component,并在实例化期间设置 property isCurrentItem . 换句话说,创建新的qml文件并为其命名,例如“ Delegate.qml ”并添加 property bool isCurrentItem

    import QtQuick 2.4
    
    Rectangle {
        property bool isCurrentItem: false
        width: parent.width
        height: 20
        color: isCurrentItem ? "gray" : "lightGray"
        Text {
            anchors.centerIn: parent
            text: index
        }
    }
    

    比你可以在ListView中使用它:

    ListView {
        model: 10
        width: 40
        height: 200
        delegate: Delegate {
            isCurrentItem: ListView.isCurrentItem
        }
    }
    

    在GridView中类似:

    GridView {
        model: 10
        width: 40
        height: 200
        delegate: Delegate {
            isCurrentItem: ListView.isCurrentItem
        }
    }
    

    你可以用同样的方式将 widthListView / GridView 提供给委托,但在这种情况下 parent.width 也可以按照你想要的方式工作 .

相关问题