Yasin
Yasin

Reputation: 619

PyQt: Add icon to right side of QListWidget item

In a QlistWidget, When using listItem.setIcon(qIcon) the icon is put on the left of the list item. How can I make it show up on the right as shown below?

enter image description here

Also another question. How can I remove the icon from the item?

Upvotes: 4

Views: 6208

Answers (2)

ekhumoro
ekhumoro

Reputation: 120578

This can be done quite easily with a simple custom item-delegate:

class ItemDelegate(QtGui.QStyledItemDelegate):
    def paint(self, painter, option, index):
        option.decorationPosition = QtGui.QStyleOptionViewItem.Right
        super(ItemDelegate, self).paint(painter, option, index)

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        ...
        self.delegate = ItemDelegate()
        self.listWidget.setItemDelegate(self.delegate)

To remove an icon from an item, just set it to a null QIcon:

listItem.setIcon(QtGui.QIcon())

Upvotes: 8

Kevin Krammer
Kevin Krammer

Reputation: 5207

For this you will need to provide your own item delegate that draws the item data like you want.

See QAbstractItemView::setItemDelegate().

You can likely use QStyledItemDelegate as your base class and let its paint() handle all aspects other than the Qt::DecorationRole (the icon) and draw that yourself.

Upvotes: 1

Related Questions