Question

Is this even possible in Qt? I have a QListWidget setup with a delegate for specific painting, and I'm attempting to have the delegate paint differently based on variables in my QListWidget's parent. I figure I can rig something up as long as I have a pointer to either, but I need to somehow get them while in the delegate's paint().

I've tried the "hack" to store a pointer in a QVariant, but it doesn't seem to be working, and I'd rather not take this approach. If I could get to the pointer to item the delegate represents, and just call item->listWidget(), this would be perfect, but it doesn't seem possible while inside the delegate.

Is there any workaround to accomplish this?

Also, just because.. sample of trying to get the void* trick to work - if this is the only way to do this, perhaps someone may see what I have wrong in it.

//Parent of QListWidget
....
QListWidgetItem *item = new QListWidgetItem();
....
QVariant v = qVariantFromValue((void *) pStitchSymbolCustom);
item->setData(Qt::UserRole + 6, v);
....


//Implemented QAbstractItemDelegate
....
MyClass* p_pointer = 
    (MyClass*)(index.data(Qt::UserRole + 6).value<void *>());
Was it helpful?

Solution

I'm not sure, if i understood your question correctly, but if you want to access the QListWidget wich contains your delegate, then i think, that the easiest way is to set the parent of the delegate as the listwidget, and then get the listwidget at any point of the delegate:

QAbstractItemDelegate * delegate = new MyItemDelegate(myListWidget);

myListWidget.setItemDelegate(delegate);

and then in the delegate code:

QListWidget * listWidget = qobject_cast<QListWidget*>(parent());

//You can do whatever you want your list here

If your object tree is deep, and you want the code to be generic and not care about where the desired parent is, you should ascend the tree automatically:

QListWidget * listWidget = 0;
QObject * object = parent();
while (object && ! listWidget) {
    // qobject_cast will succeed once the parent of the correct type is reached
    listWidget = qobject_cast<QListWidget*>(object);
    object = object->parent();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top