【问题标题】:QT Text.WordWrap not working inside ColumnLayoutQT Text.WordWrap 在 ColumnLayout 中不起作用
【发布时间】:2026-02-02 17:00:01
【问题描述】:

我正在使用 QT QML 开发应用程序。 QML 我面临一个奇怪的问题。我想使用 QML 分割和显示长文本。我正在使用QT Text 元素来执行此任务。我想将此 Text 与其他 UI 元素一起放在 QT Columnlayout 中。我无法将长文本显示为多行文本。请帮我解决这个问题。这是我的 QML 代码。

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: "#18d28a"

    ColumnLayout{
        id: base_coloumn_layout
        width: parent.width
        Layout.margins: 10

        Text {
            id: application_instruction
            width: 640
            text: qsTr("xyxvx dgdgdh dhdgdd dhdgdhhgd dhhhdgd dhdgdg dhdgdh djhddh djddgdhgdh dhdgdhgdgh dhgdgdhj dhdgdghdg dhjdgdgd.")
            color: "#000000"
            font.pointSize: 12
            wrapMode: Text.WordWrap
        }
    }
}

当放置在ColoumnLayout 之外时,相同的元素可以正常工作。我可以使用下面的代码将文本显示为多行。我希望相同的代码应该像 ColoumnLayout 的子级一样工作,因为 ColoumnLayout 内的元素会更少

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
color: "#18d28a"

    Text {
        id: application_instruction
        width: 640
        text: qsTr("xyxvx dgdgdh dhdgdd dhdgdhhgd dhhhdgd dhdgdg dhdgdh djhddh djddgdhgdh dhdgdhgdgh dhgdgdhj dhdgdghdg dhjdgdgd.")
        color: "#000000"
        font.pointSize: 12
        wrapMode: Text.WordWrap
    }
}

ColoumnLayout 有什么问题。我是否缺少要设置的任何属性值。请帮忙

【问题讨论】:

    标签: c++ qt qml


    【解决方案1】:

    在 ColumnLayout 中,宽度属性被忽略。

    改为设置 Layout.preferredWidthLayout.maximumWidth Text 元素的附加属性。

    如果您希望某个项目填充 ColumnLayout 的宽度,可以将 Layout.fillWidth 附加属性设置为 true

    【讨论】:

    • 非常感谢 Mark ch,在完成上述更改后,我得到了想要的输出。
    • 我刚刚看了你的答案...还有另一种可能更合适的方式,我会添加它....
    【解决方案2】:

    根据 Mark 给出的答案,我们可以将 qml 更改为下面给出的,我们可以显示多行文本。

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    import QtQuick.Layouts 1.0
    
    ApplicationWindow {
        id: application_window
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        color: "#18d28a"
        ColumnLayout {
            id: base_coloumn_layout
            width: parent.width
            Layout.margins: 10
            Text {
                id: application_instruction
                width: application_window.width
                Layout.preferredWidth: application_window.width
                text: qsTr("xyxvx dgdgdh dhdgdd dhdgdhhgd dhhhdgd dhdgdg dhdgdh djhddh djddgdhgdh dhdgdhgdgh dhgdgdhj dhdgdghdg dhjdgdgd.")
                color: "#000000"
                font.pointSize: 12
                wrapMode: Text.WordWrap
            }
        }
    }
    

    【讨论】: