Add QIcon to QTableView cell

730 views Asked by At

I have already coded this for QTableWidget:

void ReadOnlyWindow::addReportIconToRow(const int rowIndex){
    QIcon icon;
    QSize sz(16, 16);

    icon.addPixmap(style()->standardIcon(QStyle::SP_FileDialogEnd).pixmap(sz), QIcon::Normal);

    QTableWidgetItem *iconItem = new QTableWidgetItem();
    iconItem->setText("report");
    iconItem->setIcon(icon);
    iconItem->setFlags(iconItem->flags() & (~Qt::ItemIsEditable));

    ui->homeWorksTable->setItem(rowIndex, REPORT_COLUMN_INDEX, icon);
}

REPORT_COLUMN_INDEX is const int from class and it has value 4.

I am trying to found out how to rewrite code if table is `` QTableView`.

I was trying to use setItemData() and setData() but I think I used it in bad way because it didn't work.

P.S.: Now I want to do it for QTableView because its easy to load SQLite table there. This part works. I also added one more column. Now I need add to all rows of this column icon with text (how is in my code for QTableWidget). Function up there should be for one cell and will be implemented in loop.

1

There are 1 answers

1
ΦXocę 웃 Пepeúpa ツ On

to add an icon to a tableWidget you set the item like specified here :

and when defining the QTableWidgetItem, use the constructor taking an Icon to be displayed.

here is a short example:

this->ui->myTable->setItem(row, col, new QTableWidgetItem(QIcon(":/resources_to_icon_.png"),"SomeText"));

in your code:

ui->homeWorksTable->setItem(rowIndex, REPORT_COLUMN_INDEX, QTableWidgetItem(icon,"some text");