[Qt-interest] 答复: how to know derive class
Oliver.Knoll at comit.ch
Oliver.Knoll at comit.ch
Thu Nov 11 09:53:58 CET 2010
On 2010-11-11 Pengliang(彭亮) pengliang(彭亮) wrote:
> Hi
> Thank you.
> But how to know which QWidget is QLineEdit and which is QComboBox?
This is actually a C++ question (or more general, an OO-question):
The general answer: use RTTI (Run-time Type Information): most compilers support that nowadays, but it adds slight overhead to your classes, and I guess even today you have to explicitly enable it by a compiler flag or so.
Refer to: http://www.devx.com/getHelpOn/Article/10202/1954 or google for "typeid()"
The Qt specific (and good answer): Qt has its own "RTTI" system already built-in (mostly because back in those days when Qt was developed not all compilers had "native" RTTI support, or it was broken etc.). Qt needs to keep track of signals/slots anyway, and it does that with its "Meta Object System":
http://doc.qt.nokia.com/4.7/metaobjects.html
There you'll find everything you want to know about "inherits()", "qobject_cast()" etc. :)
Attention: EVERY class in a class hierarchy needs the Q_OBJECT macro defined in its class declaration (when you want to check the type of your own classes)! Even if it does not make use of signals/slots of its own! Only when the Q_OBJECT macro is present in the class declaration then the proper "runtime information" is added to that class. This can't be stressed enough.
And for obvious reasons that only works for QObject based classes - luckily that is just the case for QWidget and QLineEdit and Co. ;)
Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22
More information about the Qt-interest-old
mailing list