簡體   English   中英

根據Delegate中的Image計算TableView的高度

[英]Calculate TableView height according to Image in Delegate

我有一個帶有以下輸出的TableView

f2cc7453-140d-42b6-9009-bfe6f00e4b4c-image.png

Item {
    property string picture
    
    //...

    id: root
    Rectangle {
        id: rect
        anchors.fill: parent
        border.width: 1
        border.color: "black"
    }

    Image {
        id: image
        anchors.centerIn: parent
        source: root.picture.length > 0 ? "data:image/png;base64," + root.picture : ""
        fillMode: Image.PreserveAspectFit
        sourceSize.width: rect.width - rect.border.width * 2
        sourceSize.height: rect.height - rect.border.height * 2
    }

    //...
}

所以我原以為Image適合Rectangle但事實並非如此。

TableView看起來像這樣:

Item {
    id: root
    
    //...
    
    HorizontalHeaderView {
        id: horizontalHeaderView
        syncView: tableView
        anchors.left: tableView.left
        model: [qsTr("Id"), qsTr("Question"), qsTr("Answer 1"), qsTr(
                "Answer 2"), qsTr("Answer 3"), qsTr("Answer 4"), qsTr(
                "Correct Answer"), qsTr("Picture")]
    }
    TableView {
        id: tableView
        width: parent.width
        height: parent.height - horizontalHeaderView.height
        anchors.top: horizontalHeaderView.bottom
        boundsBehavior: Flickable.StopAtBounds

        reuseItems: true
        clip: true
        property var columnWidths: [60, 220, 220, 220, 220, 220, 100, 140]
        columnWidthProvider: function (column) {
            return columnWidths[column]
        }

        model: questionsProxyModel

        delegate: DelegateChooser {
            id: chooser

            //... More DelegateChoices here for the other columns but not 
            //.. interesting for the issue here
            DelegateChoice {
                column: 7
                delegate: PictureDelegate {
                    id: pictureDelegate
                    width: tableView.columnWidthProvider(column)
                    picture: model.picture
                }
            }
        }
        ScrollBar.vertical: ScrollBar {}
    }
}

所以在TableView我通過columnWidthProvider為每個委托提供寬度,這工作正常。

高度是根據孩子的內容自動計算的。 例如,這可確保所有文本始終適合:

a167dac0-0785-4e24-a37c-499b216aff5f-image.png

現在我怎樣才能考慮到委托中的Image需要適當縮放的heigth

該問題可以通過使Rectangle成為Image的根並使用anchors.fill而不是anchors.centerIn

Rectangle {
    property string picture
    
    //...

    color: "transparent"
    border.width: 1
    border.color: "black"
    id: root


    Image {
        id: image

        anchors.fill: parent
        anchors.margins: root.border.width

        source: root.picture.length > 0 ? "data:image/png;base64," + root.picture : ""
        fillMode: Image.PreserveAspectFit
    }

    //...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM