如何在应用程序启动时将 QML TableView 列的大小调整为其内容?

How to resize QML TableView column to its contents on app start?

我在 Ubuntu 18.04 上使用 Qt 5.9.4。

当我的应用程序启动时,我想根据其内容自动调整 TableView 的列大小。模型在开始时有一些数据。

我知道 resizeColumnToContents 函数,但我不知道在哪里调用它。

onDataChange does not work in TableView: QML 引擎说这个信号不存在。但是intellitype允许我在代码中输入它。

如何实现?

编辑 2018 年 9 月 18 日

如果您使用 StackView,或者您可以预加载您的 TableView

// main.qml

Loader {
   id: tableViewLoader
   active: true
   sourceComponent: TableView { id: tableView }
}

StackView {
id: stackView
initialItem: listViewLoader

function onContentReceived()
{
    stackView.push(tableViewLoader);
    tableViewLoader.item.resizeColumnsToContents()
}

function onContentClosed()
{
    swipeView.pop()
}

}

编辑 2018 年 9 月 17 日

你是对的丹尼尔。

TableView.qml中指定

Depending on how the model is populated, the model may not be ready when
TableView Component.onCompleted is called. In that case you may need to
delay the call to positionViewAtRow by using a \l {QtQml::Timer}{Timer}

对我来说这是有效的

Component.onCompleted: resizeColumnsToContentsTimer.start()

Timer {
    id: resizeColumnsToContentsTimer
    interval: 50
    running: false
    repeat: false
    onTriggered: parent.resizeColumnsToContents()
}

你也可以看到这个关于它的讨论

http://lists.qt-project.org/pipermail/interest/2016-June/023018.html


也许,您可以在设置模型时调用的 onModelChanged 中调用它(您的模型必须在之前填充)。

onModelChanged: tableView.resizeColumnToContents()

否则,您可以在数据准备好后使用signals/slots。

但要注意这个函数:如果你有委托,你必须在其中指定 implicitWidth,否则这将不起作用。

headerDelegate: Rectangle {
    id: headerDelegate
    height: 36
    implicitWidth: textItem.implicitWidth + textItem.padding * 2
    color: Style.lightColor

    Text {
        id: textItem
        anchors.fill: parent
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignLeft
        padding: 10
        text: styleData.value
        elide: Text.ElideRight
        color: Style.darkColor
        font.pixelSize: Style.bigFontPixelSize
    }
}