PDA

View Full Version : How to add an QObject to QListWidget



steg90
14th May 2007, 15:16
Hi,

Is it possible to add an object to a list widget item? In MFC I generally attach objects to items in a list, example ( this is from MFC ):



m_MessageList.SetItemDataPtr( nIndex, (void*)pMess );


Where pMess is of type CMessage ( own class ) and m_MessageList is of CListBox.

Best regards,
Steve

jpn
14th May 2007, 15:23
You can store anything a QVariant can hold as user data:


// QVariant data;
// QListWidgetItem* item;
item->setData(Qt::UserRole, data);


See Q_DECLARE_METATYPE() (http://doc.trolltech.com/4.2/qmetatype.html#Q_DECLARE_METATYPE) in case built-in datatypes supported by QVariant are not enough.

steg90
14th May 2007, 15:25
Hi,

Thanks, that is exactly what I just did :)

Now, having trouble getting the item data back.



CDADcb::CMessage* pMess = ui.messageList->item(i)->data(Qt::UserRole);


Keeps saying cannot convert to CDADcb::CMessage from QVariant, I've tried casting this but to no avail.

Kind regards,
Steve

jpn
14th May 2007, 15:30
Try:


CDADcb::CMessage* pMess = ui.messageList->item(i)->data(Qt::UserRole).value<CDADcb::CMessage*>();

steg90
14th May 2007, 15:34
Thanks JPN, you're a star :D

BTW, did have to do the following in the class header :



Q_DECLARE_METATYPE(CDADcb::CMessage*)

steg90
14th May 2007, 15:42
Problem now is, pMess is always NULL?

This is how I set up the list box :



CDADcb::CMessage* pMess = (CDADcb::CMessage*)i.value();
if( pMess )
{
QListWidgetItem *newItem = new QListWidgetItem;
newItem->setFlags( newItem->flags() | Qt::ItemIsUserCheckable );
newItem->setCheckState(Qt::Unchecked);
newItem->setText( pMess->name );
newItem->setData( Qt::UserRole, pMess );
ui.messageList->insertItem( ui.messageList->count(), newItem);
}


Dunno what is wrong???

Regards,
Steve

jpn
14th May 2007, 15:49
newItem->setData( Qt::UserRole, QVariant::fromValue(pMess) );
:)

steg90
14th May 2007, 15:53
Once again, many thanks for all your great help, now works a treat :rolleyes:

Kind regards,
Steve