PDA

View Full Version : setData()



coderbob
28th February 2008, 09:14
I have a QAction that I wish to use setData() on so I can reference a QWidget at a later date rather then using a QHash for a lookup table.


QAction *act = new QAction(this);

QWidget *randomWidget = new QWidget(this);

act->setData(randomWidget);


Problem is when I want to get that QWidget back and use it. If I try to cast it


QWidget *returnWidget = qobject_cast<QWidget *>(act->data());

I get "error: no matching function for call to ‘qobject_cast(QVariant)’"

If I try to set it directly


QWidget *widget = act->data();

I get "error: cannot convert ‘QVariant’ to ‘QWidget*’ in initialization".

In QVariant docs I am allowed to set my own user type data; so am I just misunderstanding the use of a QVariant?

Bob

jpn
28th February 2008, 11:14
See QVariant::value() or qvariant_cast (http://doc.trolltech.com/4.3/qvariant.html#qvariant_cast). But notice also QAction::associatedWidgets().

coderbob
28th February 2008, 12:04
After my failed attempts I cannot seem to cast the QVariant back to a QWidget.

Using

qVariantValue<QWidget>(act->data());

Gives me multiple errors of
1. error: ‘QWidget::QWidget(const QWidget&)’ is private
2. error: ‘qt_metatype_id’ is not a member of ‘QMetaTypeId<QWidget>’

If I use my own custom structure then there is no problem, and if I use QColor and the like from the document examples there is not a problem.

I need a QWidget * back and I cannot seem to get it to cast it correctly. It must be getting really late because after going over the docs and examples I cannot for the life of me figure out how to get a QWidget * cast correctly.

Q_DECLARE_METATYPE(QWidget); also results in an epic fail.

Bob

ChristianEhrlicher
28th February 2008, 12:34
It's a pointer, not an object!

coderbob
28th February 2008, 12:51
@jpn QAction::associatedWidgets() will not work as the QWidgets are not associated in that manner with the QAction.

@ChristianEhrlicher I tried qVariantValue<QWidget *>(act->data()); to no avail but through the magic of sleep deprivation after your post on another attempt it worked. :D