ASi
ASi

Reputation: 11

What does "window = qobject_cast<QWindow *>(root)" mean?

I have some code that works but I don't understand the meaning of this pattern:

QWindow * window;
if (window = qobject_cast<QWindow *>(root))
  window->show();

Upvotes: 0

Views: 220

Answers (2)

The code translates to the following pseudo-code:

if (root is an instance of `QWindow` set window to that instance)
  show that window;

The qobject_cast works exactly like dynamic_cast, but only applies to QObject-derived classes and works even when runtime type information is not available (e.g. for small builds on MSVC, or on some embedded platforms).

Upvotes: 0

Pavel Strakhov
Pavel Strakhov

Reputation: 40512

qobject_cast is Qt's alternative of dynamic_cast for QObject-based classes. root is a pointer to some object. In your case it probably has QObject* or QWidget* type. However, the code expects that it may in fact be a QWindow* object. qobject_cast checks if the object is an instance of QWindow class or any class inherited from it, and returns 0 if that's not the case. If the check is successful, qobject_cast returns QWindow* pointer to the object, and the code can use it to call QWindow-specific methods that are not available through QObject* or QWidget* pointer.

Upvotes: 3

Related Questions