qt tablewidget设置图片

如何在qt的tablewidgetitem中设置图片
2024-12-02 15:28:30
推荐回答(2个)
回答1:

有多种方法:

用图标的方式:  

    QTableWidgetItem *it = ui->tableWidget->item(row, col);
    if (it==0)
    {
       it=new QTableWidgetItem();
       setItem(row, col, it);
    }    
    it->setIcon(QIcon(pixMap));

用setCellWidget: 

   QLabel* label=new QLabel;
   label->setPixmap(pixMap);
   ui->tableWidget->setCellWidget(row, col, label);

用代理:

class QPixmapItemDele : public QStyledItemDelegate
{
public:
     QPixmapItemDele(QObject* parent = 0) : QStyledItemDelegate(parent) {}
     virtual void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
     {
         if (index.data(Qt::DisplayRole).canConvert())
         {
             QPixmap pm = index.data(Qt::DisplayRole).value();
             painter->drawPixmap(0,0,pm);
         }
         else
         {
             QStyledItemDelegate::paint(painter, option, index);
         }
     }
};
......
ui->tableWidget->setItemDelegate(new QPixmapItemDele);
ui->tableWidget->item(row,col)->setData(Qt::DisplayRole, QVariant::fromValue(pixMap));

回答2:

方法如下:

用图标的方式:

QTableWidgetItem *it = ui->tableWidget->item(row, col);
if (it==0)
{
it=new QTableWidgetItem();
setItem(row, col, it);
}
it->setIcon(QIcon(pixMap));

用setCellWidget:

QLabel* label=new QLabel;
label->setPixmap(pixMap);
ui->tableWidget->setCellWidget(row, col, label);

用代理:

class QPixmapItemDele : public QStyledItemDelegate
{
public:
QPixmapItemDele(QObject* parent = 0) : QStyledItemDelegate(parent) {}
virtual void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
if (index.data(Qt::DisplayRole).canConvert())
{
QPixmap pm = index.data(Qt::DisplayRole).value();
painter->drawPixmap(0,0,pm);
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
}
};
......
ui->tableWidget->setItemDelegate(new QPixmapItemDele);
ui->tableWidget->item(row,col)->setData(Qt::DisplayRole, QVariant::fromValue(pixMap));