Summary of experience in upgrading QT project to QT6 hematemesis

Time:2021-10-23

QT versions have been released more and more frequently. QT6 has been released for some time. More and more people are asking whether the previous code can increase support for QT6, including the open source project qwidgetdemo (more than 2.6k star a year). Recently, in their busy schedule, they have upgraded the compatibility of QT6 for all projects. Since then, all projects have been compatible from QT4 to QT6, which takes more than a month, In total, there are more than 10000 lines of update adjustment code. Although the update workload is not very large, it still wastes the strength of nine cows and two tigers. After all, there are too many projects. One of the dozens of project works has 188 sub projects. In order to facilitate myself and summarize and share experience, I specially sorted out some experience points from QT4 compatibility to QT6, which is only part. It will be updated continuously in the later stage. You are also welcome to leave a message for supplement.

Intuitive summary

  • Many wheels are added, and the original modules are split more carefully. It is estimated that in order to facilitate the expansion of management.
  • Some over encapsulated things are removed (for example, the same function has multiple functions), ensuring that only one function performs the function.
  • Some methods compatible with QT4 in Qt5 are abandoned, and the corresponding new functions in Qt5 must be used.
  • Following the pace of the times, many new features have been added to meet the growing needs of customers.
  • Some modules, types and processing have been revolutionary rewritten, and the operation efficiency has been improved a lot.
  • There are changes in parameter types, such as long * to qintptr *, which are more suitable for subsequent expansion and compatibility with different 32-64 bit systems at the same time.
  • The double data type in the source code is replaced by qreal, which is highly consistent and unified with the internal data type of QT.
  • I tested the QWidget part, but not the quick part. It is estimated that there may be more updates to the quick part.
  • It is strongly recommended not to use the version between qt6.0 and qt6.2 for the time being. Some modules are still missing and there are relatively many bugs. It is recommended to start the formal migration of version 6.2.

summarize experience

  1. Universal method: install version 5.15, locate the error reporting function, switch to the source terminal file, and you can see the corresponding prompt QT_ DEPRECATED_ X (“use sizeinbytes”) and the new function. It’s right to modify according to this prompt class. Some functions are newly added from qt5.7, 5.9, 5.10 and other versions. Maybe your project still uses QT4 methods, but QT6 is compatible with these old methods before. At QT6, you need to use new methods completely.
  2. QT6 splits the core class into more core5compats. Therefore, you need to add the corresponding module in pro and introduce the corresponding header file into the code.
//Pro file import module
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
greaterThan(QT_MAJOR_VERSION, 5): QT += core5compat

//Introducing header files into code
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
#include <QtWidgets>
#endif
#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
#include <QtCore5Compat>
#endif

3. By default, QT6 enables high score screen support, and the interface will become large and even the font will be false. Many people will not be used to this mode, because if many coordinate calculations of the program do not use devicepixelratio, 100% of the problems will occur because the coordinates are inaccurate. To cancel this effect, you can set the high screen zoom factor.


#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
    QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::Floor);
#endif

4. The original random number function prompts to use qrandomgenerator instead. In order to be compatible with all QT versions, the least change is to directly use the random number in C + +, such as qsrand function to srand, qrand function to RAND. After checking the source code, it actually encapsulates the random number in C + +, and many similar packages, such as sin encapsulated by qsin.

5. Change the light of qcolor to lighter and the dark to dark. In fact, the two methods of lighter and dark have always existed before.

6. Replace fm.width in qfontmetricsf with fm.horizontaladvance, and use the new function from 5.11.

7. Qpalette palette enumeration values, foregroup = windowtext, background = window, where foregroup and background are not available, and windowtext and window are used to replace them. Similarly, SetTextColor is changed to setforegroup.

8. Change delta() of qwheelevent to angledelta(). Y(), and pos() to position().

9. SVG module is split into svgwidgets. If this module is used, QT + = svgwidgets needs to be added in Pro.

10. Replace the margin() function in qllayout with contentsmargins(). Left(). Check the source code. It is known that the previous margin() returns contentsmargins(). Left(). When the four values are the same, the four values are the same by default. Similarly, setmargin is removed, and setcontentsmargins is used for everything.

11. Before qchar C = 0xf105, all qchar C = (qchar) 0xf105 should be changed into forced conversion. There is no implicit conversion, otherwise the compilation error prompt error: conversion from ‘Int’ to ‘qchar’ is ambiguous.

12. Some functions such as qsort use STD:: sort of C + +.


#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
    std::sort(ipv4s.begin(), ipv4s.end());
#else
    qSort(ipv4s);
#endif

13.Qt::WA_ Change nobackground to QT:: wa_ OpaquePaintEvent 。

14. The Qmatrix class is abandoned and replaced with qtransform. The functions are basically the same. The qtransform class has been available since QT4.

15. Qtime timing is removed and needs to be changed to qelapsedtimer. Qelapsedtimer class has been available since QT4.

16. QApplication:: desktop() is abandoned and replaced by QApplication:: primaryscreen().


#if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
#include "qscreen.h"
#define deskGeometry qApp->primaryScreen()->geometry()
#define deskGeometry2 qApp->primaryScreen()->availableGeometry()
#else
#include "qdesktopwidget.h"
#define deskGeometry qApp->desktop()->geometry()
#define deskGeometry2 qApp->desktop()->availableGeometry()
#endif

17. Obtaining the current screen index and size needs to be processed separately.

//Get current screen index
int QUIHelper::getScreenIndex()
{
    //Multiple screens need to be processed
    int screenIndex = 0;
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
    int screenCount = qApp->screens().count();
#else
    int screenCount = qApp->desktop()->screenCount();
#endif

    if (screenCount > 1) {
        //Find the current mouse screen
        QPoint pos = QCursor::pos();
        for (int i = 0; i < screenCount; ++i) {
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
            if (qApp->screens().at(i)->geometry().contains(pos)) {
#else
            if (qApp->desktop()->screenGeometry(i).contains(pos)) {
#endif
                screenIndex = i;
                break;
            }
        }
    }
    return screenIndex;
}

//Gets the current screen size area
QRect QUIHelper::getScreenRect(bool available)
{
    QRect rect;
    int screenIndex = QUIHelper::getScreenIndex();
    if (available) {
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
        rect = qApp->screens().at(screenIndex)->availableGeometry();
#else
        rect = qApp->desktop()->availableGeometry(screenIndex);
#endif
    } else {
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
        rect = qApp->screens().at(screenIndex)->geometry();
#else
        rect = qApp->desktop()->screenGeometry(screenIndex);
#endif
    }
    return rect;
}

18. The qregexp class is moved to the core5compat module, and the header file #include needs to be actively introduced。

19. The construction parameters of qwheelevent and the corresponding calculation azimuth function have changed.

//Analog mouse wheel
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
QWheelEvent wheelEvent(QPoint(0, 0), -scal, Qt::LeftButton, Qt::NoModifier);
#else
QWheelEvent wheelEvent(QPointF(0, 0), QPointF(0, 0), QPoint(0, 0), QPoint(0, -scal), Qt::LeftButton, Qt::NoModifier, Qt::ScrollBegin, false);
#endif
QApplication::sendEvent(widget, &wheelEvent);

//The mouse wheel directly modifies the value
QWheelEvent *whellEvent = (QWheelEvent *)event;
//The angle of scrolling, * 8 is the distance the mouse scrolls
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
int degrees = whellEvent->delta() / 8;
#else
int degrees = whellEvent->angleDelta().x() / 8;
#endif
//The number of scrolling steps, * 15 is the mouse scrolling angle
int steps = degrees / 15;

20. Change qvariantvalue to qvariant_ Cast, qvariantsetvalue (V, value) changed to v.setvalue (VAL). It is equivalent to going back to the original method. Looking at the qvariant value source code, qvariant is encapsulated_ cast。

21. The init of qstyleoption is changed to initfrom.

22. Qvariant:: type is replaced by qmetatype:: type. The previous qvariant:: type encapsulates qmetatype:: type.

23. Qstyleoptionviewitem V2 V3 V4 and other items are not available. Qstyleoptionviewitem can be used instead for the time being.

24. An overloaded function of qfont’s resolve is replaced by resolvemask.

25. The setinicodec method of qssettings is removed. It defaults to utf8 and does not need to be set.

26. The activated (qstring) and currentindexchanged (qstring) signals of qcombobox are deleted. The one with the int index parameter is used to obtain the value through the index. Personally, I don’t think it’s necessary to delete this.

27. The qtscript module is completely gone. Although it was prompted as an abandoned module from the later version of the Qt5 era, it was not officially abandoned until QT6. All JSON data parsing was replaced by qjson class parsing.

28. The qstring parameter overload function of many methods such as qbytearray append indexof lastIndexOf is abandoned. To directly transfer qbytearray, add. Toutf8() on the basis of the original parameters. Looking at the source code, we can see that the previous qstring parameter is also converted to. Toutf8 () for comparison.

29. Time conversion function totime of qdatetime_ t + setTime_ The name of T is changed to tosecssinceepoch + setsecssinceepoch. These two methods were added in qt5.8.

30. The pixmap function of qlabel used to be the pointer * pixmap(), but now it is replaced by the reference pixmap().

31. The sortbycolumn method of qtablewidget removes the default ascending method. The second parameter must be filled in to indicate ascending or descending order.

32. The error signal error in qtnetwork is replaced by erroreoccurred.

33. The xmlpatterns module is available, and all are re parsed with the XML module.

34. The parameter type of nativeevent has changed.


#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0))
bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result);
#else
bool nativeEvent(const QByteArray &eventType, void *message, long *result);
#endif

This is the end of this article about the experience of upgrading QT project to QT6 hematemesis. For more information about upgrading QT project to QT6, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]