【问题标题】:How to resize QML TableView column to its contents on app start?如何在应用程序启动时将 QML TableView 列的大小调整为其内容?
【发布时间】:2019-02-18 16:53:57
【问题描述】:

我在 Ubuntu 18.04 上使用 Qt 5.9.4。

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

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

onDataChangeTableView 中不起作用:QML 引擎说此信号不存在。但智能型允许我在代码中输入它。

如何做到这一点?

【问题讨论】:

    标签: qt qml tableview qt5 column-width


    【解决方案1】:

    编辑 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
        }
    }
    

    【讨论】:

    • 它不起作用:在调用信号时onModelChangedTableView 的列计数为零。
    • 另外,我试过Timer。它仅在 interval 设置为 2000 毫秒时才有效。当然,这是不可接受的。
    猜你喜欢
    • 2012-08-05
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 2017-06-08
    相关资源
    最近更新 更多