Подтвердить что ты не робот

Как заставить элементы QML расти в соответствии с содержанием?

Как заставить 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 }
    }
}
4b9b3361

Ответ 1

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

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 не имеют размера, не имеют позиции, а этот столбец, строка, поток, сетка, текст и размер изображения сами по себе относятся к их контенту, поэтому, если вы хотите использовать Column для изменения размера его детей, вы должны убедиться, что размер столбца больше не определяется автоматически одним из его дочерних элементов. Потому что в другом месте дети останутся 0x0, а столбец также будет 0x0. Столбец должен быть привязан к его родительскому объекту, чтобы иметь реальный размер, а его дети должны привязываться горизонтально (влево и вправо) в столбец, чтобы иметь реальную ширину, а для элементов высоты нужно их самостоятельно определять в соответствии с их внутренней компоновкой...

Ответ 2

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

import QtQuick 1.0

Column {
    id: serverItem

    BorderImage {
        anchors.fill: parent
    }

    //... the rest
}

Ответ 3

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