如何使用QML的RichText中的html源中心图片?

时间:2016-03-10 10:10:18

标签: c++ qt qml

我想使用RichText将图片置于QML中心。我尝试了<center>代码和text-align属性。它们都不起作用。

import QtQuick 2.0
import QtQml.Models 2.1
import QtQuick.Window 2.2
import QtQuick.Controls 1.2


ApplicationWindow{
    width: Screen.width; height: Screen.height; color: "#d5d6d8"
    visible:true
    Rectangle {
        color: "#33cc94"
        width: parent.width; height: parent.height
        id : main

        Flickable {
            id:textArea
            anchors.fill: parent
            contentHeight: textBrowser.height
            contentWidth: textBrowser.width
            enabled: false
            Text {
                id:textBrowser
                textFormat: Text.RichText
               // visible:false
             //   text: "<center><img src=\"Icons/TroopCards/ArchersCard.png\"  /></center>";
                text: "<p style=\"text-align:center\">
                          <img  src=\"Icons/TroopCards/ArchersCard.png\" />
                       </p>
                       <p style=\"text-align:center\">Some text at middle</p>";
            }
        }
    }
}

结果:

Left aligned image!

如何在QML中使用html居中图像?!

4 个答案:

答案 0 :(得分:2)

如果需要在块的中心放置一些东西,请指定块的宽度(和高度),以便程序可以计算中心位置。例如,将文本块的大小设置为Screen大小:

Text {
    id:textBrowser
    textFormat: Text.RichText
    width: Screen.width
    height: Screen.height
    text: "<p style=\"text-align:center\"><img src=\"Icons/TroopCards/ArchersCard.png\" /></p>
           <p style=\"text-align:center\">Some text at middle</p>";
}

现在图片在窗口中居中(因为ApplicationWindow具有相同的宽度和高度)。

......不,它没有。也许富文本处理器中存在一些错误,或者它根本不支持富文本中的图像对齐。如果您真的想使用富文本将图像放在文本块的中心,这里有一个简单的解决方法:在图像标记之前加上&nbsp;(空格字符)。

Text {
    id:textBrowser
    textFormat: Text.RichText
    width: Screen.width
    height: Screen.height
    text: "<p style=\"text-align:center\">&nbsp;<img src=\"Icons/TroopCards/ArchersCard.png\" /></p>
           <p style=\"text-align:center\">Some text at middle</p>";
}

图像几乎位于文本块的中心。

答案 1 :(得分:0)

试试这个:

Text {
            id:textBrowser
            anchors.horizontalCenter: parent.hrizontalcenter
            textFormat: Text.RichText
            text: "<p style=\"text-align:center\">
                      <img  src=\"Icons/TroopCards/ArchersCard.png\" />
                   </p>
                   <p style=\"text-align:center\">Some text at middle</p>";
        }

答案 2 :(得分:0)

text的{​​{1}}参数(TextAreaText)一起试用:

textFormat: Text.RichText

答案 3 :(得分:0)

对于锚点,您可以使用窗口宽度(主)减去周围元素(父)宽度除以2来计算Text元素的水平中心偏移量。所以,添加以下三行:

horizontalAlignment: Text.AlignHCenter
anchors.horizontalCenterOffset: (main.width - parent.width) / 2
anchors.horizontalCenter: parent.horizontalCenter

结果:

result