Coreggon
Coreggon

Reputation: 555

Alignment of text in Qt Combobox

I have a combobox in Qt and some items in it. Now the problem is, when the text is too long and the item is selected, the right side of the item is shown and I want to show the left side (the beginning) of the text and ... at the end (the rest of the text that won't fit in the box will not be shown) Is there a way of doing this? . I have been searching the whole internet and documentations but I did not find a proper answer. Thanks.

Upvotes: 0

Views: 1673

Answers (1)

Mitch
Mitch

Reputation: 24406

There's no easy way to do this currently. You need to provide a custom delegate for the ComboBox itself, and then override its contentItem to be able to set the elide property:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: window
    visible: true
    width: 400
    height: 400

    ComboBox {
        id: comboBox
        model: [ "some really really really long text", "some really really really long text" ]
        delegate: ItemDelegate {
            id: itemDelegate
            width: parent.width
            text: comboBox.textRole ? (Array.isArray(comboBox.model) ? modelData[comboBox.textRole] : model[comboBox.textRole]) : modelData
            font.weight: comboBox.currentIndex === index ? Font.DemiBold : Font.Normal
            highlighted: comboBox.highlightedIndex === index
            hoverEnabled: comboBox.hoverEnabled

            contentItem: Label {
                text: itemDelegate.text
                font: itemDelegate.font
                elide: Label.ElideRight
                verticalAlignment: Label.AlignVCenter
            }
        }
    }
}

I copied the delegate implementation from here.

I think it could make sense for ItemDelegate (or rather AbstractButton, so that all of its derivatives could benefit from it) to have an elide property, so that it's one less custom item.

Upvotes: 1

Related Questions