Centered and sortable icons in QTableWidget
-
Hello,
I'm desperately looking for a solution to be able to display icons in a QTableWidget column so that the icons are BOTH centered and sortable.
Centering looks not possible via a normal QTableWidgetItem(QIcon()) so I rather use a QLabel and set the item via setCellWidget() method.
iconItem = QtWidgets.QLabel() iconItem.setPixmap(iconPixmap) iconItem.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) myTableWidget.setCellWidget(x, y, iconItem)
But I didn't find any solution to sort such QLabel items in a QTableWidget column.
Sorting QTableWidgetItem icons is relatively easy by subclassing QTableWidgetItem, but here I didn't find any solution to center them, all the icons are stuck on the left side of the cells.
iconItem = QtWidgets.QTableWidgetItem() # Sorting is easy by subclassing iconItem.setIcon(QtGui.QIcon(iconPixmap)) iconItem.setTextAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) # Has NO effect on icon centering myTableWidget.setItem(x, y, iconItem)
Note my table has many other columns, with text and numbers.
If anyone has an idea I would be very grateful, thanks a lot for your help.
-
Hi,
Another solution could be to implement your own QStyledItemDelegate to paint your icon the way you want it. That way the sorting will be available.
-
@SGaist Thank you very much for that suggestion! Looks promising, however this looks a bit complicated, the doc is quite obscure and I couldn't find any obvious PyQT examples for such technic. If you would have some sample usages to share that could help me that would be super great. Thanks again for your help.
-
Did you check the Star Delegate example ? It's not yet ported to Python but is a pretty simple implementation to follow.