Won Xu, Yu Cheng, Shen Kaiyang
Qt is introduced
Qt is a cross-platform C++ graphical user interface application framework. It as early as 1991, trolltech company two partners working on such a platform, in 2008, the reigning due to bullish on Qt potential in the field of embedded, nokia could buy it as a carrier of a new generation of intelligent mobile phone operating system, but because nokia’s defeat in the field of smart phones, having let go Qt, Qt was acquired by Digia in 2012. After several years of development, Qt not only has a complete C++ graphics library, but also greatly improve the Qt development of cross-platform applications.
Qt can support desktop application development, embedded development and mobile development at the same time, and it can even do mobile development, covering all major existing platforms. You only need to write the code once and recompile it before releasing it to a different platform.
Which products are developed using Qt?
Qt’s GUI library and rich API library support for native Windows, Mac, Linux and other platforms make it a good choice for developing cross-platform desktop applications. Different from some excellent desktop software in China who choose to develop their own multi-platform GUI library, many excellent desktop applications abroad prefer to develop cross-platform GUI library. For example, in Silicon Valley, there is a famous document management application DropBox, Microsoft’s own social chat tool Skype, GUI pages of large games like Need for Speed, even the Office software WPS Office launched by Kingsoft In China, and of course, AlphaBox.
Why does AlphaBox choose Qt?
Qt can not only efficiently complete the development of GUI content for different platforms, but also efficiently complete some system-level tasks. This is why AlphaBox chose to use Qt for development.
AlphaBox actually contains two main processes, one is the synchronization engine of the disk – the low-level synchronization process built by C language, we call it daemon; The rest of the graphical pages and modules that interact with the operating system were developed using Qt. Qt provides rich cross-platform GUI components to ensure that AlphaBox has a beautiful and consistent style of operating system in different operating systems. Qt Creator, an IDE produced by Qt itself, provides a very easy to use graphical interface building tool. Even those who are new to Qt can easily draw the desired page and complete the core page logic. In addition, thanks to the support of C++, Qt has a very robust communication mechanism with the operating system. With this, AlphaBox can easily complete precise monitoring of file changes in the operating system, establish a local database for writing data, and other operations. The excellent hybrid programming capability makes it easy to mix Qt with objective-C, C# and other languages to implement system-level extension calls, which is why you can see different states of sync disk files in Finder and Windows Explorer.
Qt advantage
Excellent cross-platform features
Qt supports Windows, Linux/Unix, Mac OS X, Android, BlackBerry, QNX and other platforms, and provides a unified development environment for these different platforms.
object-oriented
C++ is fully object-oriented, much like development in Objective-C etc. Qt is based on C++ a language extension, we all know that C++ has fast, simple, object-oriented and many other advantages, so Qt is the natural successor to C++ these advantages.
Qt good packaging mechanism makes Qt modular degree is very high, good reuse, is very convenient for users to develop goods. Qt provides a security type called signals/slots instead of callback to make it easy to work together between components.
Rich API
Qt includes more than 250 C++ classes. It also provides template-based collections, serialization, file, I/Odevice, directory management, and date/time classes. It even includes regular expression processing. Support 2D/3D graphics rendering, support OpenGL. Extensive development documentation.
XML support
The integration of the Webkit engine allows for seamless integration of the native interface with Web content, but really makes Qt the most useful tool in the free software world for Widgets such as Lesstif, Gtk, EZWGL, Xforms, FLTK, etc.) is the heavyweight qt-based software KDE.
Signal and slot mechanism
Qt provides a signal and slot mechanism to complete the response to the meet operation, which is the communication mechanism to complete any two Qt objects. A slot is equivalent to a function that receives and processes a signal that is triggered in a particular situation or action.
Why methods are not called directly. Isn’t it unnecessary to use Signal and slot?
In fact, it is the same in our life. It is easy for the boss to talk, and it is also easy for the boss to assign tasks to his assistant, but the assistant gives tasks to the boss. It can be imagined what the consequences will be. Therefore, in the idea of layering, the function we call is also like this. The upper layer can call the functions of the lower layer and the same layer, but the lower function can not call the upper function, otherwise the hierarchical nature of the program will be broken, resulting in a complex structure, difficult to maintain and manage.
So how do you manage up, when you have tasks to delegate to your boss?
The boss would set up a mechanism, a function, that would use an infinite loop to check the assistant’s status, and if the assistant did have a problem, the mechanism would bring the information to the boss. However, this approach is a bit complicated, and we want to keep it simple: if the assistant has an event, we can call the boss function directly to handle it.
All that said, the biggest advantage of signals and slots is that they improve the idea of layering programs, making it possible to call from one layer to the next without changing the program’s layering. Send a Signal at the lower level, and the Slot function that the upper level wants to associate with it responds.
Now, the problem with signals and slots is:
- The object that sends the signal is only responsible for sending it, but it does not know who receives the signal;
- The slot in the receiving object itself is just an ordinary member function, which does not know which signal to respond to;
To solve the above problem, the corresponding signal and slot need to be connected. When the specified signal is emitted, the slot object receives the signal and calls the corresponding slot function to perform the specified processing.
The way the signal is connected to the slot
1. One signal can be connected to another signal
connect (Object1,SIGNAL(signal1),Object2,SIGNAL(signal2));
Copy the code
Signal 1 sending of Object1 triggers signal 1 sending of Object2.
2. The same signal can be connected to multiple slots:
connect (Object1,SIGNAL(signal2),Object2,SIGNAL(slot2));
connect (Object1,SIGNAL(signal2),Object3,SIGNAL(slot1));
Copy the code
3. The same slot can respond to multiple signals:
connect (Object1,SIGNAL(signal2),Object2,SIGNAL(slot2));
connect (Object3,SIGNAL(signal2),Object2,SIGNAL(slot2));
Copy the code
4. Connections can be removed:
This is rarely used because Qt automatically removes all connections associated with an object when it is deleted.
disconnect(sender, SIGNAL(signal), receiver, SLOT(slot));
Copy the code
However, the common connection mode is as follows:
connect (Object1,SIGNAL(signal),Object2,SIGNAL(slot));
Copy the code
Signal indicates the signal of Object1, and slot indicates the slot of Object2.
#### tip: The signal and slot mechanism, like ordinary function calls, can cause an infinite loop when the program executes if not used properly. Therefore, when defining the slot function, care must be taken to avoid forming an indirect infinite loop, that is, transmitting the same received signal again in the slot. If a signal is associated with multiple slots, the order in which the associated slots are activated when the signal is emitted will be random. Macro definitions cannot be used in parameters of signal and slot. The number and type of signal and slot parameters must be consistent.
Signal and slot mechanism advantages
Type safety
The signature of the signal and slot to be associated must be identical. That is, the parameter types and numbers of the signal are the same as those of the slot that receives the signal. However, the number of parameters in a slot can be less than the number of parameters in the signal, but the missing parameter must be the last or several parameters in the signal parameter. If the signal does not match the slot signature, the compiler will report an error.
Loose coupling
The signal and slot mechanism greatly reduces the coupling of Qt objects. The Qt object that sends the signal does not need to know which object is receiving its signal, all it needs to do is send a signal at the appropriate time, and it does not need to know or care whether its signal is received or not, and it does not need to know which object in which slot is receiving the signal.
Similarly, slots of Qt objects do not need to be related to which signals are connected to them. If signals are connected to slots, Qt ensures that the appropriate slots are called. Even if the associated object is deleted at run time. Applications don’t crash.
Signal and slot efficiency
The signal and slot mechanism enhances the flexibility of communication between objects, but of course there is a loss in performance while increasing flexibility. The signal and slot mechanism is a bit slow compared to your callbacks. In general, calling a slot function by passing a signal will run 10 times slower than calling a non-virtual function directly.
The reason:
- The object receiving the signal needs to be located.
- Safely traverse all associations.
- Marshalling/unmarshalling passed parameters.
- Multithreading. Signals may need to be queued up.
However, signals and slots are only a fraction of the cost of running them compared to new operations that create heap objects and DELETE operations that delete heap objects. This small performance loss due to the signal and slot mechanism is negligible for real-time applications; This performance loss is well worth the flexibility and simplicity provided by signals and slots.
Qt layout system introduction
Layout system
As an iOS developer, I have witnessed the continuous improvement of iOS layout system, from absolute layout, Autoresizing to Autolayout. It makes the work efficiency of the developers higher and higher, and the readability and easy maintenance of the project interface stronger and stronger. Now IDE visual interface tools have been very powerful, many users “jokingly” iOS developers as “UI drag division “, visible, iOS development interface layout system efficient. Therefore, the mission of a good layout system is to allow developers to achieve a more maintainable interface in less time.
Similarly, in Qt, the system provides a powerful typesetting mechanism for the window view layout typesetting, after a preliminary exploration of Qt layout, have to express admiration of the Qt layout system’s simplicity, efficiency and powerful function.
Layout system functions
In Qt, the layout system can be done
- Positioning child control
- Get the default form size
- Get the minimum window size
- Type the layout when the form size changes
- Content changes (font size text, etc., hidden or displayed, removed) when the layout is typeset
Layout the structure of the system
Qt provides the QLayout class and its subclasses to layout an interface. The structure is as follows:
QLayout is an abstract base class in the layout system, which inherits from QObject and QLayoutItem
- QBoxLayout
- QFormLayout
- QGridLayout
- QStackedLayout
In real use scenarios, it is often necessary to complete the interface design through the combination of various layouts. Next, four layouts will be introduced respectively.
QBoxLayout Box layout
Box layout provides two subclasses to handle horizontal (QHBoxLayout) and vertical (QVBoxLayout) layouts, which allow views to be displayed in a row or column. For example, in our AlphaBox, the head, name, and refresh buttons are arranged in a row at the top. This is the horizontal box layout:
You think I’m going to talk about how this thing works? NO, I’m going to use the vertical box layout as an example and use the simplest example to introduce the use of the box layout. First, create a QWidget-based interface and add the header file we need to use:
#include <QVBoxLayout>
#include <QPushButton>
Copy the code
Add the following code to the constructor
// Add two buttons
QPushButton *okBtn = new QPushButton;
okBtn ->setText(tr("I'm on top. I'm the best."));
QPushButton *celBtn = new QPushButton;
celBtn->setText(tr("I'm down here. I'm not giving in."));
// Create a vertical box layout and drop the two buttons into it
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(okBtn);
layout->addWidget(celBtn);
// Set the layout of the interface to vertical box layout
setLayout(layout);
Copy the code
Let’s run it and see what happens. What? So this is going to work, right? Coordinates? Size? Yes, that’s right… Click Run:
Two buttons have been up and down, obediently in the vertical direction of their own standing position, is so powerful, is so easy.
QFormLayout Form layout
The powerful AlphaBox is very outgoing, you can easily share your data to other users, when we share, there will be such an interface:
See this interface, smart you may say, this is very simple, several horizontal box layout can be implemented, but the smarter Qt provides a more efficient way to help you complete such an interface, that is QFormLayout.
In the books I used to learn Qt, QFormLayout is translated into forms layout. I personally think it is more appropriate to translate it into forms layout, because the strength of QFormLayout is the fastest way to complete the construction of a user input form interface.
So let’s demystify AlphaBox and see how such an interface is implemented.
First, drag and drop a Form Layout into the Widget.
Double-click to add a line to the form.
When you see this picture, you can already understand how the form layout is used. It provides labels as a guide for user input, and provides field types as controls for user input. As an iOS developer, you know how much work it takes to build such an interface. When I first opened the interface, I was blown away by the way it was created.
- Create the first line of the form as shown in the figure, share the input box with which user, and fill in the placeholder text for the input box.
- Double-click The Form Layout to create a row with the field type QComboBox. Enter the permission content.
- Set the entire Widget layout to a vertical box layout
- Drag and drop a Horizontal Layout under Form Layout
- Add Horizontal Spacer to the box layout and drag two Push buttons to complete the interface layout
Fast unhappy? Quick unhappy! Unhappy!!!!!!
Similarly, if you are using a pure code form layout you can use the addRow() method to add a line.
QGridLayout Grid layout
In fact, the power of AlphaBox is such that we can share with multiple users, and there is a list of shared users and a list of permissions below. At this point, the form layout can not satisfy us, we have to find a new favorite QGridLayout – grid layout.
Grid layout, as the name suggests, allows you to split the interface into rows for layout management, placing controls in each cell. So AlphaBox’s shared interface uses a grid layout of two rows and three columns.
Of course, the more complex interface, with Qt layout efficiency is also very high, I made an external chain to share the layout Demo, can generate a download link to share the internal data to anyone to download.
In this interface, I used a grid layout within the Tab, as shown below:
As you can see from the diagram, grid layout is as simple as operating an Excel, arranging cells, merging cells, and so on.
In this interface, the more flexible use of QLayout attributes to complete the layout of the interface.
Similarly, in code, you can add a control to a grid view that occupies several rows and columns, starting with several rows and columns, using apis like the following:
void addWidget(QWidget *, int row, int column, int rowSpan, int columnSpan)
Copy the code
QStackedLayout stack layout
For example, in AlphaBox, we can view and operate cloud files directly through the cloud file browser. During the loading process, there will be an interface to switch chrysanthemum.
Error message when loading failed:
And when loading is successful:
QStackedLayout is a stack layout that provides a stack of pages, with each page having a completely separate layout. Can be very clear to different states of the interface layout management.
In Qt’s visual layout tool, Stacked Widgets are used to complete the stack layout of the interface
Insert, remove, and sort pages by right clicking.
The last
In the following articles, we will introduce Qt development in more depth by module, starting with the build project. Stay tuned!