首页 > 解决方案 > 如何让 TableView 的列占据所有父级

问题描述

我们怎样才能使列占据父级的所有大小?我为什么要问这个?因为正如我们在一个简单的示例中看到的那样,列并没有填满表格的所有大小,这很丑陋。

我不想发生在列上的唯一一件事就是让它的宽度小于其列的内容。

我希望该解决方案适用于许多列。

我们怎样才能成功地做到这一点?

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Controls 1.4
    import QtQuick.Layouts 1.3
import QtQuick.Controls.Styles 1.1

ApplicationWindow {
    id: window
    title: "Stack"
    visible: true
    width: 1400
    ListModel {
        id: libraryModel
        ListElement {
            title: "A Masterpiece"
            author: "Gabriel"
        }
        ListElement {
            title: "Brilliance"
            author: "Jens"
        }
        ListElement {
            title: "Outstanding"
            author: "Frederik"
        }
    }

    Page {
        id: page
        anchors.fill: parent
        TableView{
            style: TableViewStyle{
                handle: Rectangle {
                    implicitWidth: 15
                    implicitHeight: 15
                    color:  "#000000"
                }
                minimumHandleLength: 30
            }
            anchors.fill:parent
            TableViewColumn {
                role: "title"
                title: "Title"
                width: 100
            }
            TableViewColumn {
                role: "author"
                title: "Author"
                width: 200
            }
            model: libraryModel
            itemDelegate: Text
            {
              text: styleData.value
              elide: Text.ElideRight
            }
        }
    }
}

已经指出了类似的答案

width: (table.width / table.columnCount) - 1

可以使用,但我不想以小宽度发生要剪切的项目/文本我希望滚动条出现:

在此处输入图像描述

标签: qtqml

解决方案


像这样 ?-1 只是为了避免看到烦人的滚动条(可能是由边距/边框引起的)

TableView{
    id: table
    anchors.fill:parent

    style: TableViewStyle{
        handle: Rectangle {
            implicitWidth: 15
            implicitHeight: 15
            color:  "#000000"
        }
        minimumHandleLength: 30
    }

    TableViewColumn {
        role: "title"
        title: "Title"
        width: (table.width / table.columnCount) - 1
    }
    TableViewColumn {
        role: "author"
        title: "Author"
        width: (table.width / table.columnCount) - 1
    }
    model: libraryModel
    itemDelegate: Text
    {
      text: styleData.value
      elide: Text.ElideRight
    }
}

推荐阅读