how to position the QIcon in the Qt table item?

≯℡__Kan透↙ 提交于 2020-07-16 04:41:25

问题


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);

回答1:


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);

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)


来源:https://stackoverflow.com/questions/52619196/how-to-position-the-qicon-in-the-qt-table-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!