Customize QListWidgetItem with extra data to store in, How?

catinred picture catinred · May 3, 2011 · Viewed 8.7k times · Source

The QListWidgetItem contains 2 data: icon and text. And I want to store another QString in it. How can I do? Here is my test code.The ListWidget displays nothing after I call addItem.

And how can I know which item is clicked? The SLOT function is "void on_listWidget_itemClicked(QListWidgetItem* item)". Obviously the parameter item is the parent class: QListWidgetItem, NOT the subclass: ListWidgetItem

ListWidgetItem::ListWidgetItem(const QIcon &icon, const QString &text,QString &ip, QListWidget *parent, int type)
{
    myip = ip;
    QListWidgetItem::QListWidgetItem(icon,text,parent,type);
}

ListWidgetItem::~ListWidgetItem()
{

}

QVariant ListWidgetItem::data(int role) const
{
    if (role==IPROLE)
    {
        return myip;
    }
    return QListWidgetItem::data(role);
}

void ListWidgetItem::setData(int role, const QVariant &value)
{
    if (role==IPROLE)
    {
        myip = value.toString();
    }
    QListWidgetItem::setData(role,value);
}

Answer

TonyK picture TonyK · May 4, 2011

QListWidgetItem has member functions

void QListWidgetItem::setData ( int role, const QVariant & value )

and

QVariant QListWidgetItem::data ( int role ) const

for storing arbitrary data (including QString). Set role = Qt::UserRole (or any higher value).