Search code examples
qtlistviewqmlqwidget

Qt, QML ListView and Desktop App


My question is kind of a two part conditional question. I have a desktop application I'm writing in C++/Qt. In the app I have a couple lists that I want to decorate and add list items with icons and rich text.

I first attempted to do this with the QWidget world but the more I looked into it, the more I thought QML might be a better option. But now I'm wondering about that as well since it seems that QML Is more geared toward touch screen devices. Not to mention that my progress with QML has been frusating. Give them QML below, I cannot figure out how to: (1) get an item to highlight when I click it and (2) add a scroll bar:

import QtQuick 1.0

Item
{
    width: 300
    height: 200

    ListModel
    {
        id: myModel2

        ListElement { text: "List Item 1" }
        ListElement { text: "List Item 2" }
        ListElement { text: "List Item 3" }
        ListElement { text: "List Item 4" }
        ListElement { text: "List Item 5" }
        ListElement { text: "List Item 6" }
    }

    Component
    {
        id: beerDelegate

        Rectangle
        {
            id: beerDelegateRectangle
            height: beerDelegateText.height * 1.5
            width: parent.width

            Text
            {
                id: beerDelegateText
                text: "<b>" + modelData + "</b> <i>(" + modelData + ")</i>"
            }

            MouseArea
            {
                anchors.fill: parent
                onClicked: 
                {
                    console.log("clicked: " + modelData + " at index: " + index);
                    beerList.currentIndex = index;
                }
            }
        }
    }

    ListView
    {
        id: beerList
        anchors.fill: parent
        model: myModel2
        delegate: beerDelegate

        highlightFollowsCurrentItem: true
        highlight: Rectangle
        {
            width: parent.width
            color: "red"
        }

        focus: true
    }
}

How can I accomplish what I'm looking for given this QML? Or is using QML in a QWidget desktop app just a bad idea all around?


Solution

  • For the first question (highlight):

    Your list actually draws the highlight, however, your item delegate overpaints this with a white rectangle! Just replace the rectangle with an item and it works:

    Component
    {
        id: beerDelegate
    
        Item
        {
            ...
        }
    }
    

    For the second question (scroll bars):

    As far as I know, QML doesn't provide scroll bars out of the box. There is however the Qt Desktop Components project (git repository) which gives you access to most of the widgets in the QML world. Among them, there is a ScrollArea.