Как заставить элементы QML расти в соответствии с содержимым? - PullRequest
26 голосов
/ 27 апреля 2011

Как заставить ServerItem расти в соответствии с содержимым?В настоящий момент ServerItems просто перекрывают друг друга.

main.qml

import Qt 4.7
import "Teeworlds" as Teeworlds

Item {
    Column {
        Teeworlds.ServerItem {
            serverName: "InstaGib, lost [xyz]"
        }

        Teeworlds.ServerItem {
            serverName: "Arena.sbor (rus)"
        }
    }
}

ServerItem.qml

import QtQuick 1.0

BorderImage {
    id: serverItem

    property string serverName: "unnamed server"
    property string gameType: "DM"
    property int numPlayers: 0
    property int maxPlayers: 8
    property int ping: 60

    Text {
        id: title
        text: parent.serverName
    }

    Grid {
        id: grid
        anchors.top: title.bottom
        columns: 2
        rows: 3
        Text { text: "Gametype: " }  Text { text: gameType }
        Text { text: "Players: " }   Text { text: numPlayers + "/" + maxPlayers }
        Text { text: "Ping: " }      Text { text: ping }
    }
}

Ответы [ 3 ]

12 голосов
/ 26 июня 2013

Необходимо указать размер для контейнеров и добавить привязки / привязки в дочерние элементы:

main.qml:

import QtQuick 1.1
import "Teeworlds" as Teeworlds

Item {
    width: 800; // root item so give a size
    height: 600;

    Flickable {
         clip: true;
         anchors.fill: parent; // use a flickable to allow scrolling
         contentWidth: width; // flickable content width is its own width, scroll only vertically
         contentHeight: layout.height; // content height is the height of the layout of items

         Column {
             id: layout;
             anchors { // the column should have a real size so make it fill the parent horizontally
                 left: parent.left;
                 right: parent.right;
             }

             Teeworlds.ServerItem {
                serverName: "InstaGib, lost [xyz]";
             }
             Teeworlds.ServerItem {
                serverName: "Arena.sbor (rus)";
             }
        }
    }
 }

Teeworlds / ServerItem.qml:

import QtQuick 1.1

BorderImage {
    id: serverItem;
    height: grid.y + grid.height; // compute the item height using content position and size
    anchors { // to have a real size, items should grow horizontally in their parent
        left: parent.left;
        right: parent.right;
    }

    property string serverName  : "unnamed server";
    property string gameType    : "DM";
    property int      numPlayers  : 0;
    property int      maxPlayers   : 8;
    property int      ping               : 60;

    Text {
        id: title;
        text: parent.serverName;
    }
    Grid {
        id: grid;
        columns: 2;
        anchors { // the grid must anchor under the title but horizontally in the parent too
            top: title.bottom;
            left: parent.left;
            right: parent.right;
        }

        Text { text: "Gametype: " } 
        Text { text: gameType }
        Text { text: "Players: " }  
        Text { text: numPlayers + "/" + maxPlayers }
        Text { text: "Ping: " }    
        Text { text: ping }
    }
}

Помните, что по умолчанию все Item, Rectangle, BorderImage не имеют размера, позиции и что сами столбцы, строки, потоки, сетки, текста и изображения соответствуют своему содержаниюпоэтому, если вы хотите использовать столбец для изменения размера его дочерних элементов, вы должны убедиться, что размер столбца больше не определяется автоматически одним из его дочерних элементов.Потому что в другом месте дети останутся 0x0, а столбец также будет 0x0.Столбец должен быть привязан к своему родителю, чтобы иметь реальный размер, а его дочерние элементы должны быть привязаны горизонтально (слева и справа) к столбцу, чтобы иметь реальную ширину, а для элементов высоты их размер должен сам соответствовать их внутреннему расположению ...

9 голосов
/ 27 апреля 2011

На самом деле это довольно просто. Объекты ServerItem не имеют размера, вы можете видеть содержимое только потому, что отсечение отсутствует. Решением было бы либо установить высоту и ширину в классе ServerItem (или экземпляры в main.qml), либо использовать растущий элемент, например, Столбец, как корневой элемент ServerItem.

import QtQuick 1.0

Column {
    id: serverItem

    BorderImage {
        anchors.fill: parent
    }

    //... the rest
}
2 голосов
/ 24 ноября 2011

Вы должны установить размер явно, чтобы два элемента QML внутри строки / столбца не перекрывались.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...