Make QML menu width fit the content

Found an implementation here and added two pixels:

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Menu {
    width: {
        var result = 0;
        var padding = 0;
        for (var i = 0; i < count; ++i) {
            var item = itemAt(i);
            result = Math.max(item.contentItem.implicitWidth, result);
            padding = Math.max(item.padding, padding);
        }
        // It looks like two pixels are missing to remove the ellipsis.
        // My first idea was that it is leftInset + rightInset, but it does not work.
        var missing = 2;
        return result + padding * 2 + missing;
    }
}

See Popup Layout:

Leave a Reply

Your email address will not be published. Required fields are marked *