Creating custom components based on the Component class
Introduction
The Component
class itself provides opportunities for creating complex components, but if this component begins to contain others, then it becomes inconvenient to copy entire pieces of code with the components. Here comes the creation of your own components based on the Component
class. In short, creating your own class hides a part of the logic by which the component is built and avoids copying the code.
Example
Let's create a Button
folder in the same folder as MyWindow
folder and add Button.h
.
To create your own components, connect the header file of the Component
class. Create a class and inherit it from Component
, overload the constructor and add the setup
method, which call in the constructor.
In the constructor, immediately add a field for the button text and write it in the text field.
The setup
method is used to configure the component; all methods of the Component
class can be called in it.
In the previous example, we used the setText
method to set the text for the component. Call this method in setup.
The setup is now finished, let's move on to adding to the window.
Connect this component to the window and add it:
Here, to add, just, the third prototype of the add
method is used.
Thus, the logic of setting the text is hidden from an external observer, and creating a component with text has become much easier.
Some requirements for an inherited component
The simplest example of inheritance was considered above, but in the future it is necessary to add another static create
method, for convenience. This method should completely repeat the constructor and, if necessary, other possible options for creating the component.
Then the addition can be rewritten as:
Connect styles in a component
Another important part of inheritance is styles.
Prior to this, all styles were connected globally for the entire window, but each component can also contain the necessary styles, thereby being completely separate from the window.
To add styles for the component, use the style
method:
Thus, the created components may not depend on the window into which they are added.
Last updated
Was this helpful?