-1

I want to set QTableWidgetItem's data as an image. imagePath may be different each time.

QTableWidgetItem *itemMedia = new QTableWidgetItem();
itemMedia->setTextAlignment(Qt::AlignCenter);
itemMedia->setData(Qt::DecorationRole, QPixmap(imagePath).scaled(width, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation));
m_table->setItem(0,0,itemMedia);
m_table->setItem(0,1,itemMedia);
m_table->setItem(1,0,itemMedia);
m_table->setItem(1,1,itemMedia);

I've created it nicely. Next, I want to get data with this:

connect(m_table, SIGNAL(itemClicked(QTableWidgetItem *)), this, SLOT(onItemClicked(QTableWidgetItem *)));

void MUCSharedMedia::onItemClicked(QTableWidgetItem *item)
{
    qDebug()<<"DecorationRole: " <<item->data(Qt::DecorationRole).toString();
    qDebug()<<"DisplayRole: " <<item->data(Qt::DisplayRole).toString();
}

Actually I want imagePath in one of this role , but I get this line in Application Console:

DecorationRole:  ""
DisplayRole:  ""

How to get value? Any suggestion?

EDITED: I want to show image on each QTableWidgetItem after that I want to store image path of images which I've shown.

Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81

3 Answers3

1

QTableWidgetItem::data() returns QVariant where you'll get the data with QVariant::value().

Alternatively, use QTableWidget::text().

http://doc.qt.io/qt-5/qtablewidgetitem.html

Acha Bill
  • 1,255
  • 1
  • 7
  • 20
1

If you need to store QString actually, you need DisplayRole two times:

itemMedia->setData(Qt::DisplayRole, imagePath);

qDebug()<<"DisplayRole: " <<item->data(Qt::DisplayRole).toString();

EDIT: if you need to show image and get image file path I suggest you another way:

1) Set image like you did:

itemMedia->setData(Qt::DecorationRole, QPixmap(imagePath).scaled(width, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation));

2) Set image path using Qt::UserRole

itemMedia->setData(Qt::UserRole, imagePath);

When you need it:

qDebug()<<"File Path: " <<item->data(Qt::UserRole).toString();

But application will use image for displaying.

demonplus
  • 5,613
  • 12
  • 49
  • 68
1

You store a QPixmap:

itemMedia->setData(Qt::DecorationRole, QPixmap(imagePath).scaled(width, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation));

but try to extract it as a QString:

qDebug()<<"DecorationRole: " <<item->data(Qt::DecorationRole).toString();

That will always give you a default-constructed (i.e. empty) QString.

You want to retrieve it as a QPixmap:

item->data(Qt::DecorationRole).value<QPixmap>()

(though there's little point sending that to a QDebug stream!)

There's a good chance you want the original, unscaled pixmap. In which case, you'll need to store that as well, perhaps in Qt::UserRole:

itemMedia->setData(Qt::UserRole, QPixmap(imagePath));

and change the retrieval to match.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103