Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a picture using html source in RichText of QML?

Tags:

c++

qt

qml

I want to center a picture in QML using RichText . I tried <center> tag and text-align attribute. none of them works.

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>";
            }
        }
    }
}

And result :

Left aligned image!

How can I center an image using html in QML ?!

like image 331
uchar Avatar asked Oct 31 '22 07:10

uchar


1 Answers

If you need to put something in the center of a block, specify the width (and height) of the block so the program can calculate the center position. For example, set the size of the text block to Screen size:

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>";
}

And the image is now centered in your window (since your ApplicationWindow has the same width and height).

......No, it doesn't. Maybe there are some bugs in the rich text processor, or maybe it does not support image alignment in rich text at all. If you really want to use rich text to put an image in the center of the text block, here is a simple workaround: put an &nbsp; (space character) before your image tag.

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>";
}

And the image is almost in the center of the text block.

like image 145
mcchu Avatar answered Nov 15 '22 06:11

mcchu