Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize QListWidgetItem with extra data to store in, How?

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);
}
like image 916
catinred Avatar asked May 03 '11 10:05

catinred


1 Answers

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).

like image 189
TonyK Avatar answered Sep 16 '22 22:09

TonyK