c++qtqt5qtablewidgetqicon

how to position the QIcon in the Qt table item?


I want a table cell with text aligned to the left and icon aligned to the right side.

But now, im getting both icon and text left aligned, here what i have tried

QtTableWidgetItem * item = new QtTableWidgetItem("program");
item -> setIcon(icon);
ui -> tableWidget -> setItem(i,j,item);

Solution

  • To manage the position of the icon and the text you must use a delegate, in this case I use the QStyledItemDelegate and I overwrite the initStyleOption() method:

    C++ version

    aligndelegate.h

    #ifndef ALIGNDELEGATE_H
    #define ALIGNDELEGATE_H
    
    #include <QStyledItemDelegate>
    
    class AlignDelegate: public QStyledItemDelegate{
    public:
        using QStyledItemDelegate::QStyledItemDelegate;
    protected:
        void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override
        {
            QStyledItemDelegate::initStyleOption(option, index);
            option->decorationPosition = QStyleOptionViewItem::Right;
        }
    };
    
    #endif // ALIGNDELEGATE_H
    

    Then it is established in the delegate:

    AlignDelegate *delegate = new AlignDelegate(ui->tableWidget);
    ui->tableWidget->setItemDelegate(delegate);
    
    QTableWidgetItem *item = new QTableWidgetItem("foo text");
    item->setIcon(icon);
    ui->tableWidget->setItem(i, j, item);
    

    enter image description here

    Python version:

    class AlignDelegate(QtWidgets.QStyledItemDelegate):
        def initStyleOption(self, option, index):
            super().initStyleOption(option, index)
            option.decorationPosition = QtWidgets.QStyleOptionViewItem.Right
    
    delegate = AlignDelegate(view)
    view.setItemDelegate(delegate)