how do i place QTableWidgetItem Icon in center of cell

I had a similar problem I solved it without sub classing by using a QLabel as cellwidget
(sadly i needed to use a layout, too):

int row = 0;
int column = 0;
QSize sizeIcon(32, 32);
QString iconSrc = ":/Actions/myicon.png";

QWidget *pWidget = new QWidget();
QLabel *label = new QLabel;
label->setMaximumSize(sizeIcon);
label->setScaledContents(true);
label->setPixmap(QPixmap(iconSrc));
QHBoxLayout *pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(label);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0,0,0,0);
pWidget->setLayout(pLayout);

this->ui->myTableWidget->setCellWidget(row, column, pWidget);

I used the following approach:
http://falsinsoft.blogspot.de/2013/11/qtablewidget-center-checkbox-inside-cell.html


You can use: setCellWidget, as follow:

QLabel *lbl_item = new QLabel();
lbl_item ->setPixmap(*ui->my_label->pixmap());
lbl_item ->setAlignment(Qt::AlignHCenter);
ui->my_tablewidget->setCellWidget(row, column, lbl_item);

This will put the Icon at the center


You can affect the position of the icon in relation to the text via the style options.

If the QTableWidgetItem is constructed without any text (via the constructor that does not accept a text argument), then the Qt::DisplayRole data item is not set and the text will not be displayed nor will it affect the icons display rectangle.

I was able to affect the position of the QTableWidgetItem's icon by subclassing the QTableWidget, overriding the viewOptions method and setting the decorationAlignment field of the view options, like this:

QStyleOptionViewItem MyTableWidget::viewOptions() const
{
    QStyleOptionViewItem option = QTableWidget::viewOptions();
    option.decorationAlignment = Qt::AlignHCenter | Qt::AlignCenter;
    option.decorationPosition = QStyleOptionViewItem::Top;
    ...
    return option;
}

Tags:

Qt

Qt4

Pyqt4