首页 > 解决方案 > 如何在应用程序启动时将 QML TableView 列的大小调整为其内容?

问题描述

我在 Ubuntu 18.04 上使用 Qt 5.9.4。

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

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

onDataChange不起作用TableView:QML 引擎说这个信号不存在。但是智能型允许我在代码中输入它。

如何做到这一点?

标签: qtqmltableviewqt5column-width

解决方案


编辑 18/09/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()
}

}

编辑 18 年 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()

否则,您可以在数据准备就绪时使用信号/插槽。

但要小心这个函数:如果你有委托,你必须指定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
    }
}

推荐阅读