-
Notifications
You must be signed in to change notification settings - Fork 0
1.03
Explanation of the contents of a topic page @ Week 1 Topic 1
Objective: Custom QObjects with properties, enums
Comment: Qt object model - identity types
E: Is this a suggestion for the topic or the objective?
E: There are some issues with this format regarding macros and hotlinks. We may either need to elaborate macros mentioned by writing them out or by hotlinking them into the text. Same issue kind of exists for class/function references within the text. Just pointing out that this is an issue that needs to be resolved as the text will feel goofy if we are mentioning stuff like Q_GADGET but there not really being any way of seeing wth it is. I did however include the explanation for Q_GADGET but I guess I'd want to put the two macros next to each other in screenshots and compare them, maybe, if it still feels relevant later on.
- What is a macro?
- What is preprocessing?
- What are value types (1.01)?
- What is the QObject class?
- What is the Meta-Object System?
- What is the Qt Object Model (does this belong here?)?
- What is the Q_OBJECT macro?
- What does subclassing mean in the context of Qt?
- What is the Property system?
- How do you declare a Property?
- How does a Property behave?
- How do you read and write Properties?
- What is the Q_ENUM macro?
- What are identity types?
- How do value types compare to identity types?
- How do identity types compare to value types?
- What is the Meta Object Compiler?
- Object introspection using the meta-object?
Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.
https://wiki.qt.io/Qt_for_Beginners#Important_macros
https://wiki.qt.io/Qt_for_Beginners#Qt_class_hierarchy
[BRIEF INTRODUCTORY TEXT ABOUT THE QOBJECT CLASS AND TWO-THREE SENTENCES ABOUT SIGNALS AND SLOTS AND HOW WE ARE GOING TO CONTINUE TALKING ABOUT THEM IN 1.05?]
Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses.
A slot is called when a signal connected to it is emitted. Slots are normal C++ functions and can be called normally; their only special feature is that signals can be connected to them.
Throughout this topic there will be mentions of signals and slots as they are deeply interconnected with objects in Qt. We will focus on the signals and slots in topic 1.05, so all you need to know for now is that objects emit signals and that those signals connect to slots in other objects.
This topic will also introduce you to a couple of macros that will be of great importance for you when ever you are using signals and slots. [COULD MAYBE LIST THOSE MACROS HERE]
- https://github.com/TestMyQt/material-outline/wiki/1.03#the-qt-object-model-and-the-qobject-class (needs editing and trimming)
- https://github.com/TestMyQt/material-outline/wiki/1.03#the-meta-object-system (needs editing and trimming)
- https://github.com/TestMyQt/material-outline/wiki/1.03#subclassing (needs all)
- https://github.com/TestMyQt/material-outline/wiki/1.03#the-property-system (needs editing and dire trimming and possibly a table)
- https://github.com/TestMyQt/material-outline/wiki/1.03#the-identity-type (needs more)
- https://github.com/TestMyQt/material-outline/wiki/1.03#identity-vs-value (needs editing, possibly more)
http://doc.qt.io/qt-5/qobject.html
http://doc.qt.io/qt-5/qobject.html#Q_OBJECT
http://doc.qt.io/qt-5/qobject.html#Q_ENUM
The QObject class is the base class of all Qt objects.
QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect(). To avoid never ending notification loops you can temporarily block signals with blockSignals(). The protected functions connectNotify() and disconnectNotify() make it possible to track connections.
E: Wondering if there is any other way to intro this since we won't be discussing signals nor slots until two topics later. It's not necessarily a problem, just making a mention out of it
QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().
E: Same issue as above, except parent-child relationships. Again emphasizing that this may not be an issue just saying that these topics are covered later so the text may need some looking at
Every object has an objectName() and its class name can be found via the corresponding metaObject() (see QMetaObject::className()). You can determine whether the object's class inherits another class in the QObject inheritance hierarchy by using the inherits() function.
When an object is deleted, it emits a destroyed() signal. You can catch this signal to avoid dangling references to QObjects.
E: Dangling pointer in 1.04
QObjects can receive events through event() and filter the events of other objects. See installEventFilter() and eventFilter() for details. A convenience handler, childEvent(), can be reimplemented to catch child events.
Last but not least, QObject provides the basic timer support in Qt; see QTimer for high-level support for timers.
The Q_OBJECT macro
[PLACEHOLDER FOR SOME KIND OF INTRODUCTION TO THE Q_OBJECT MACRO THAT DOESNT FEEL REPETITIVE OR THAT REWRITES THE STUFF UNDER THE ACTUAL MACRO OR THATS THE TEXT UNDER THE MACRO SO WE TAKE IT FROM THERE AND PUT IT HERE INSTEAD]
For example:
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
Note: This macro requires the class to be a subclass of QObject. Use Q_GADGET instead of Q_OBJECT to enable the meta object system's support for enums in a class that is not a QObject subclass.
The Q_GADGET macro is a lighter version of the Q_OBJECT macro for classes that do not inherit from QObject but still want to use some of the reflection capabilities offered by QMetaObject. Just like the Q_OBJECT macro, it must appear in the private section of a class definition.
Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.
E: This needs a subtopic or subtopic removal for Q_OBJECT macro or else this transition will feel awkward
All Qt widgets inherit QObject. The convenience function isWidgetType() returns whether an object is actually a widget. It is much faster than qobject_cast<QWidget *>(obj) or obj->inherits("QWidget").
E: Are we even going to mention widgets? Is the text above necessary?
Some QObject functions, e.g. children(), return a QObjectList. QObjectList is a typedef for QList<QObject *>.
A QObject instance is said to have a thread affinity, or that it lives in a certain thread. When a QObject receives a queued signal or a posted event, the slot or event handler will run in the thread that the object lives in.
Note: If a QObject has no thread affinity (that is, if thread() returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.
E: Thread affinity - either elaborate, keep a short explanation or omit entirely. Only copying a small nudge about it from the documentation for QObject class, if we need more about thread affinity we can copypaste more from there. There was however talks about leaving thread affinity for later, so I'm not copying it's entirety here
No Copy Constructor or Assignment Operator
QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value on the Qt Object Model page.
The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.
Auto-Connection
Qt's meta-object system provides a mechanism to automatically connect signals and slots between QObject subclasses and their children. As long as objects are defined with suitable object names, and slots follow a simple naming convention, this connection can be performed at run-time by the QMetaObject::connectSlotsByName() function.
uic generates code that invokes this function to enable auto-connection to be performed between widgets on forms created with Qt Designer. More information about using auto-connection with Qt Designer is given in the Using a Designer UI File in Your Application section of the Qt Designer manual.
Dynamic Properties
From Qt 4.2, dynamic properties can be added to and removed from QObject instances at run-time. Dynamic properties do not need to be declared at compile-time, yet they provide the same advantages as static properties and are manipulated using the same API - using property() to read them and setProperty() to write them.
From Qt 4.3, dynamic properties are supported by Qt Designer, and both standard Qt widgets and user-created forms can be given dynamic properties.
Internationalization (I18n)
All QObject subclasses support Qt's translation features, making it possible to translate an application's user interface into different languages.
To make user-visible text translatable, it must be wrapped in calls to the tr() function. This is explained in detail in the Writing Source Code for Translation document.
http://doc.qt.io/qt-5/metaobjects.html
http://doc.qt.io/qt-5/qmetaobject.html
(http://doc.qt.io/qt-5/moc.html)
http://doc.qt.io/qt-5/model-view-programming.html
*E: [I REALLY HAVE NO IDEA WHAT IM SUPPOSED TO WRITE HERE OR IF THE LINK ABOVE IS EVEN RELEVANT TO THESE INTERESTS]
http://doc.qt.io/qt-5/properties.html
Qt provides a sophisticated property system similar to the ones supplied by some compiler vendors. However, as a compiler- and platform-independent library, Qt does not rely on non-standard compiler features like __property or [property]. The Qt solution works with any standard C++ compiler on every platform Qt supports. It is based on the Meta-Object System that also provides inter-object communication via signals and slots. We will be further discussing object communication and signals and slots in topic 1.05.
Requirements for Declaring Properties
To declare a property, use the Q_PROPERTY() macro in a class that inherits QObject.
Q_PROPERTY(type name
(READ getFunction [WRITE setFunction] |
MEMBER memberName [(READ getFunction | WRITE setFunction)])
[RESET resetFunction]
[NOTIFY notifySignal]
[REVISION int]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool]
[CONSTANT]
[FINAL])
Here is an example showing how to export member variables as Qt properties using the MEMBER keyword. Note that a NOTIFY signal must be specified to allow QML property bindings. We will talk more about QML next week!
Q_PROPERTY(QColor color MEMBER m_color NOTIFY colorChanged)
Q_PROPERTY(qreal spacing MEMBER m_spacing NOTIFY spacingChanged)
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged)
...
signals:
void colorChanged();
void spacingChanged();
void textChanged(const QString &newText);
private:
QColor m_color;
qreal m_spacing;
QString m_text;
A property behaves like a class data member, but it has additional features accessible through the Meta-Object System.
- A READ accessor function is required if no MEMBER variable was specified. It is for reading the property value. Ideally, a const function is used for this purpose, and it must return either the property's type or a const reference to that type. e.g., QWidget::focus is a read-only property with READ function, QWidget::hasFocus().
- A WRITE accessor function is optional. It is for setting the property value. It must return void and must take exactly one argument, either of the property's type or a pointer or reference to that type. e.g., QWidget::enabled has the WRITE function QWidget::setEnabled(). Read-only properties do not need WRITE functions. e.g., QWidget::focus has no WRITE function.
- A MEMBER variable association is required if no READ accessor function is specified. This makes the given member variable readable and writable without the need of creating READ and WRITE accessor functions. It's still possible to use READ or WRITE accessor functions in addition to MEMBER variable association (but not both), if you need to control the variable access.
- A RESET function is optional. It is for setting the property back to its context specific default value. e.g., QWidget::cursor has the typical READ and WRITE functions, QWidget::cursor() and QWidget::setCursor(), and it also has a RESET function, QWidget::unsetCursor(), since no call to QWidget::setCursor() can mean reset to the context specific cursor. The RESET function must return void and take no parameters.
- A NOTIFY signal is optional. If defined, it should specify one existing signal in that class that is emitted whenever the value of the property changes. NOTIFY signals for MEMBER variables must take zero or one parameter, which must be of the same type as the property. The parameter will take the new value of the property. The NOTIFY signal should only be emitted when the property has really been changed, to avoid bindings being unnecessarily re-evaluated in QML, for example. Qt emits automatically that signal when needed for MEMBER properties that do not have an explicit setter.
- A REVISION number is optional. If included, it defines the property and its notifier signal to be used in a particular revision of the API (usually for exposure to QML). If not included, it defaults to 0. The DESIGNABLE attribute indicates whether the property should be visible in the property editor of GUI design tool (e.g., Qt Designer). Most properties are DESIGNABLE (default true). Instead of true or false, you can specify a boolean member function.
- The SCRIPTABLE attribute indicates whether this property should be accessible by a scripting engine (default true). Instead of true or false, you can specify a boolean member function.
- The STORED attribute indicates whether the property should be thought of as existing on its own or as depending on other values. It also indicates whether the property value must be saved when storing the object's state. Most properties are STORED (default true), but e.g., QWidget::minimumWidth() has STORED false, because its value is just taken from the width component of property QWidget::minimumSize(), which is a QSize.
- The USER attribute indicates whether the property is designated as the user-facing or user-editable property for the class. Normally, there is only one USER property per class (default false). e.g., QAbstractButton::checked is the user editable property for (checkable) buttons. Note that QItemDelegate gets and sets a widget's USER property. The presence of the CONSTANT attibute indicates that the property value is constant. For a given object instance, the READ method of a constant property must return the same value every time it is called. This constant value may be different for different instances of the object. A constant property cannot have a WRITE method or a NOTIFY signal. The presence of the FINAL attribute indicates that the property will not be overridden by a derived class. This can be used for performance optimizations in some cases, but is not enforced by moc. Care must be taken never to override a FINAL property.
E: I might want to make an easily glanceable table with key features out of this if it's feasible.
The READ, WRITE, and RESET functions can be inherited. They can also be virtual. When they are inherited in classes where multiple inheritance is used, they must come from the first inherited class.
The property type can be any type supported by QVariant, or it can be a user-defined type. In this example, class QDate is considered to be a user-defined type.
Q_PROPERTY(QDate date READ getDate WRITE setDate)
Because QDate is user-defined, you must include the <QDate> header file with the property declaration.
For historical reasons, QMap and QList as property types are synonym of QVariantMap and QVariantList.
Reading and Writing Properties with the Meta-Object System
A property can be read and written using the generic functions QObject::property() and QObject::setProperty(), without knowing anything about the owning class except the property's name. In the code snippet below, the call to QAbstractButton::setDown() and the call to QObject::setProperty() both set property "down".
QPushButton *button = new QPushButton;
QObject *object = button;
button->setDown(true);
object->setProperty("down", true);
Accessing a property through its WRITE accessor is the better of the two, because it is faster and gives better diagnostics at compile time, but setting the property this way requires that you know about the class at compile time. Accessing properties by name lets you access classes you don't know about at compile time. You can discover a class's properties at run time by querying its QObject, QMetaObject, and QMetaProperties.
QObject *object = ...
const QMetaObject *metaobject = object->metaObject();
int count = metaobject->propertyCount();
for (int i=0; i<count; ++i) {
QMetaProperty metaproperty = metaobject->property(i);
const char *name = metaproperty.name();
QVariant value = object->property(name);
...
}
In the above snippet, QMetaObject::property() is used to get metadata about each property defined in some unknown class. The property name is fetched from the metadata and passed to QObject::property() to get the value of the property in the current object.
A Simple Example
Suppose we have a class MyClass, which is derived from QObject and which uses the Q_OBJECT macro in its private section. We want to declare a property in MyClass to keep track of a priority value. The name of the property will be priority, and its type will be an enumeration type named Priority, which is defined in MyClass.
We declare the property with the Q_PROPERTY() macro in the private section of the class. The required READ function is named priority, and we include a WRITE function named setPriority. The enumeration type must be registered with the Meta-Object System using the Q_ENUM() macro.
The macro registers an enum type with the meta-object system. It must be placed after the enum declaration in a class that has the Q_OBJECT or the Q_GADGET macro. For namespaces use Q_ENUM_NS() instead.
For example:
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
~MyClass();
enum Priority { High, Low, VeryHigh, VeryLow };
Q_ENUM(Priority)
void setPriority(Priority priority);
Priority priority() const;
};
Enumerations that are declared with Q_ENUM have their QMetaEnum registered in the enclosing QMetaObject. You can also use QMetaEnum::fromType() to get the QMetaEnum.
Registered enumerations are automatically registered also to the Qt meta type system, making them known to QMetaType without the need to use Q_DECLARE_METATYPE(). This will enable useful features; for example, if used in a QVariant, you can convert them to strings. Likewise, passing them to QDebug will print out their names.
Registering an enumeration type makes the enumerator names available for use in calls to QObject::setProperty(). We must also provide our own declarations for the READ and WRITE functions. The declaration of MyClass then might look like this:
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)
public:
MyClass(QObject *parent = 0);
~MyClass();
enum Priority { High, Low, VeryHigh, VeryLow };
Q_ENUM(Priority)
void setPriority(Priority priority)
{
m_priority = priority;
emit priorityChanged(priority);
}
Priority priority() const
{ return m_priority; }
signals:
void priorityChanged(Priority);
private:
Priority m_priority;
};
The READ function is const and returns the property type. The WRITE function returns void and has exactly one parameter of the property type. The meta-object compiler enforces these requirements.
Given a pointer to an instance of MyClass or a pointer to a QObject that is an instance of MyClass, we have two ways to set its priority property:
MyClass *myinstance = new MyClass;
QObject *object = myinstance;
myinstance->setPriority(MyClass::VeryHigh);
object->setProperty("priority", "VeryHigh");
In the example, the enumeration type that is the property type is declared in MyClass and registered with the Meta-Object System using the Q_ENUM() macro. This makes the enumeration values available as strings for use as in the call to setProperty(). Had the enumeration type been declared in another class, its fully qualified name (i.e., OtherClass::Priority) would be required, and that other class would also have to inherit QObject and register the enumeration type there using the Q_ENUM() macro.
A similar macro, Q_FLAG(), is also available. Like Q_ENUM(), it registers an enumeration type, but it marks the type as being a set of flags, i.e. values that can be OR'd together. An I/O class might have enumeration values Read and Write and then QObject::setProperty() could accept Read | Write. Q_FLAG() should be used to register this enumeration type.
Dynamic Properties
QObject::setProperty() can also be used to add new properties to an instance of a class at runtime. When it is called with a name and a value, if a property with the given name exists in the QObject, and if the given value is compatible with the property's type, the value is stored in the property, and true is returned. If the value is not compatible with the property's type, the property is not changed, and false is returned. But if the property with the given name doesn't exist in the QObject (i.e., if it wasn't declared with Q_PROPERTY()), a new property with the given name and value is automatically added to the QObject, but false is still returned. This means that a return of false can't be used to determine whether a particular property was actually set, unless you know in advance that the property already exists in the QObject.
Note that dynamic properties are added on a per instance basis, i.e., they are added to QObject, not QMetaObject. A property can be removed from an instance by passing the property name and an invalid QVariant value to QObject::setProperty(). The default constructor for QVariant constructs an invalid QVariant.
Dynamic properties can be queried with QObject::property(), just like properties declared at compile time with Q_PROPERTY().
Properties and Custom Types
Custom types used by properties need to be registered using the Q_DECLARE_METATYPE() macro so that their values can be stored in QVariant objects. This makes them suitable for use with both static properties declared using the Q_PROPERTY() macro in class definitions and dynamic properties created at run-time.
Adding Additional Information to a Class
Connected to the property system is an additional macro, Q_CLASSINFO(), that can be used to attach additional name--value pairs to a class's meta-object, for example:
Q_CLASSINFO("Version", "3.0.0")
Like other meta-data, class information is accessible at run-time through the meta-object; see QMetaObject::classInfo() for details.
The identity type derives from QObject. It exxtends C++ with many dynamic features using a meta-object system It cannot be copied as the copy constructor and assignment operator equal to delete Examples include: QWidget, QWindow, QApplication, QEventLoop, QThread, QFile, QTcpSocket.
http://doc.qt.io/qt-5/object.html#qt-objects-identity-vs-value
Some of the added features listed above for the Qt Object Model, require that we think of Qt Objects as identities, not values. Values are copied or assigned; identities are cloned. Cloning means to create a new identity, not an exact copy of the old one. For example, twins have different identities. They may look identical, but they have different names, different locations, and may have completely different social networks.
Then cloning an identity is a more complex operation than copying or assigning a value. We can see what this means in the Qt Object Model.
A Qt object:
- might have a unique QObject::objectName(). If we copy a Qt Object, what name should we give the copy?
- has a location in an object hierarchy. If we copy a Qt Object, where should the copy be located?
- can be connected to other Qt Objects to emit signals to them or to receive signals emitted by them. If we copy a Qt Object, how should we transfer these connections to the copy?
- can have new properties added to it at runtime that are not declared in the C++ class. If we copy a Qt Object, should the copy include the properties that were added to the original?
For these reasons, Qt Objects should be treated as identities, not as values. Identities are cloned, not copied or assigned, and cloning an identity is a more complex operation than copying or assigning a value. Therefore, QObject and all subclasses of QObject (direct or indirect) have their copy constructor and assignment operator disabled.
Create a class Student that has the student's name as QString and amound of study credits as integer. Use a student number (int) as the key in the container. Student should have setName(QString) and setCredits(int) as well as the respective getters.
-
Function that creates Students and adds them to the container. void addStudent(QString name, int credits, int studentNumber)
-
Function that iterates over the container and returns a list of all names who have >= credits. QStringList findByCredits(int credits)
-
Removes all students with a student numer divisible by N. QMap<int, Student> removeDivisibleStudents(int divisor)
-
Counts the amount of students with a name starting with a char. int countStudentsStartingWith(char n)