QML ScrollView with ColumnLayout

可紊 提交于 2020-01-11 05:13:09

问题


I am trying to create a scroll view around a ColumnLayout, unfortunately my current code doesn't work. I know about ListView, but in my case I need to create scrollable Layout, because it will contain heterogeneous elements.

ApplicationWindow {
    id: mainwindow
    title: qsTr("Hello World")
    width: 300
    height: 300
    visible: true

    ScrollView {
        anchors.fill: parent

        ColumnLayout {
            width: mainwindow.width

            Image {
                anchors.bottomMargin: 10
                source: "img/button.jpg"
                width: parent.width
                height: 400
            }

            Image {
                source: "img/button.jpg"
                width: parent.width
                height: 500
            }
        }
    }
}

This renders to this (which is clearly not what I want):

There are two problems:

  1. Images are not stretched across the entire window width, parent.width is ignored. I want images to have exact same width as ScrollView (no horizontal scroll)
  2. Image height property is ignored

What am I doing wrong?


回答1:


I would go with a plain column and access the desired width property directly by id. As I understand these container elements are measuring their size depending on their content, that might be the reason why setting the ColumnLayouts width has no effect.

This works for me:

ScrollView 
{
    anchors.fill: parent

    Column {

        Repeater {
            model: 4;
            delegate: Item {
                width: root.width;
                height: image.sourceSize.height;

                Image {
                    id: image;
                    anchors.centerIn: parent;
                    width: parent.width;
                    fillMode: Image.Stretch;
                    source: "img" + (index+1) + ".png"
                }
            }
        }
    }
}

In my case root is just the parent's id. Hope this helps!




回答2:


Same problem on my side. This worked for me :

ScrollView {
    width: parent.width
    height : parent.height
    contentWidth: column.width    // The important part
    contentHeight: column.height  // Same
    clip : true                   // Prevent drawing column outside the scrollview borders

    Column {
        id: column
        width: parent.width

        // Your items here
    }
}


来源:https://stackoverflow.com/questions/30656717/qml-scrollview-with-columnlayout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!