Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QListWidget - Center icon



  • Hi,

    I use a QListWidget to navigate in a QDialog (Configuration). How I can set the icon and text inside a item horizontal center?
    I use for the QListwidget:

    @contentsWidget = new QListWidget;
    contentsWidget->setViewMode(QListView::IconMode);
    contentsWidget->setIconSize(QSize(48, 48));
    contentsWidget->setMovement(QListView::Static);
    contentsWidget->setMaximumWidth(128);
    contentsWidget->setFlow(QListView::TopToBottom);@

    And with the item I use @setTextAlignment(Qt::AlignHCenter);@

    But the icon and text is always shown at the left hand border. What is the trick to show them centered?

    Ingo



  • Hi pixbyte,

    If you want to align your icons horizontally, I'm not sure this is possible with a QListView (even harder with a QListWidget).

    An idea would be to create your own custom delegate, inheriting QItemWidget. If your want to create your own, you can have a look at the doLayout protected method of QItemDelegate.

    Another would be to "hide" your QListWidget in a container with the look you want, and resize/change the position of your QListWidget to obtain the wanted result (typically by centering it in your fake parent container). Have a look at "Qt style sheets":http://doc.qt.digia.com/qt/stylesheet.html then.



  • I did that using my own delegate indeed. I reimplemented sizeHint and paint to get it to work. I simply did my own rendering of the item, making centering trivial.



  • True, that's an interesting/simple option. The only drawback is loosing the original look of items/icons.



  • There is no need to loose that look. I still have the nice glass-like selection and highlight working for my implementation, using a very simple trick. To render the highlight, I created a QStringListModel with a single item of an empty string. Now, in my paint method, I then call the base class implementation (QStyledItemDelegate) with the index of this empty item. That takes care of properly rendering the highlight.


Log in to reply