C++ API changes

Qt 5 introduces some source incompatible changes. Here we list some important ones, but you can find more complete lists in <Qt 5 Install Dir>/qtbase/dist/changes-5.x.x.

The following sections list the API changes in each module and provide recommendations for handling those changes.

Changes to Qt Core

  • QLibrary::resolve() now returns a function pointer instead of void pointer.
  • QLibraryInfo::buildKey() and the corresponding QT_BUILD_KEY macro are removed. You must remove all references to this function and macro, as build key is not necessary now.
  • The QTranslator::translate() function signature is changed to set the default value of n to -1. We recommend you to update the implementation of this virtual function in your sources.
  • QBool is removed. In Qt 4, QString::contains(), QByteArray::contains(), and QList::contains() returned an internal QBool type so that the Qt3 code if (a.contains() == 2) would not compile anymore. If your code uses QBool, replace it with bool.
  • The QUuid::operator QString() implicit conversion operator is removed. Use the QUuid::toString() function instead.
  • QProcess::ForwardedChannels no longer forwards the output to the GUI applications on the Windows platform, unless those applications create a console.
  • QSystemLocale is not public anymore. Use QLocale instead.
  • Default value of the QSortFilterProxyModel::dynamicSortFilter property is changed to true.
  • QTextCodecPlugin is removed as all the text codecs are part of Qt Core now.
  • QFSFileEngine, QAbstractFileEngine, QAbstractFileEngineIterator, and QAbstractFileEngineHandler are no longer public. We recommend you to avoid using these classes as there is no compatibility promise.
  • qDebug(), qWarning(), qCritical(), and qFatal() are changed to macros now to track the origin of the message in source code. The information to be printed can be configured (for the default message handler) by setting the new QT_MESSAGE_PATTERN environment variable. qInstallMsgHandler() is deprecated, so we recommend using qInstallMessageHandler() instead.
  • QPointer is changed to use QWeakPointer. The old guard mechanism has been removed, which causes a slight change in behavior when using QPointer. In earlier Qt versions, if a QPointer is used on a QWidget (or a subclass of QWidget), the QPointer was cleared by the QWidget destructor. In Qt 5, the QPointer is cleared by the QObject destructor along with the QWeakPointers. Any QPointer tracking a widget is not cleared before the QWidget destructor destroys the children for the widget being tracked.
  • Qt::WFlags is deprecated, use Qt::WindowFlags instead. This typedef dates from the Qt 1 days, and such abbreviations are not current Qt style.
  • Qt::HANDLE typedef is now defined as void * on all platforms.
  • The non-atomic convenience methods of QAtomicInt and QAtomicPointer (that is, operator=, operator int, operator T*, operator!, operator==, operator!=, and operator->) have been removed as they performed implicit loads and stores of unspecified memory ordering. Code dealing with loading and storing is expected to use load(), loadAquire(), store(), and storeRelease(), instead.
  • The return type of QFlags<Enum>::operator int() matches the enum's underlying type (signed or unsigned) instead of always being int. This allows QFlags over enums of the unsigned type (for example, Qt::MouseButton).
  • Because of major changes in the behavior of QTextBoundaryFinder::boundaryReasons(), the StartWord and EndWord enum values were replaced with the StartOfItem and EndOfItem values to enforce revision of the affected code.
  • A number of functions in <QtAlgorithms> are deprecated. Use the implementations available in the STL, as described in Porting Guidelines.
  • setSharable() and isSharable() in Qt containers are deprecated and will be removed in Qt 6. You should not use them in new applications. If you used them in existing applications, even though they are not documented, you should port away from them.

Changes to QAction

The Softkeys API is removed, so the following functions and enums are removed:

  • QAction::setSoftKeyRole()
  • QAction::softKeyRole()
  • QAction::SoftKeyRole
  • Qt::WA_MergeSoftkeys
  • Qt::WA_MergeSoftkeysRecursively
  • Qt::WindowSoftkeysVisibleHint
  • Qt::WindowSoftkeysRespondHint

Changes to QChar

Changes to QCoreApplication

  • QCoreApplication::translate() no longer returns the source text if the translation is empty. Use the Qt Linguist Release tool (lrelease -removeidentical) instead for optimization.
  • QCoreApplication::setEventFilter() and QApplication::x11EventFilter/macEventFilter/qwsEventFilter/winEventFilter are replaced with QCoreApplication::installNativeEventFilter() and QCoreApplication::removeNativeEventFilter() for an API much closer to QEvent filtering.

    Note: The native events that can be filtered this way depend on the QPA backend chosen at runtime. On X11, XEvents are replaced with xcb_generic_event_t due to the switch to XCB, which requires porting the application code to XCB as well.

  • QCoreApplication::Type and QApplication::type() are removed. These Qt 3 legacy application types did not match the application types available in Qt 5. Use qobject_cast instead to dynamically find out the exact application type.
  • QCoreApplication::hasPendingEvents and QAbstractEventDispatcher::hasPendingEvents are deprecated.

Changes to QEvent

  • QEvent::AccessibilityPrepare, QEvent::AccessibilityHelp, and QEvent::AccessibilityDescription are removed.
  • QEvent::TouchCancel is introduced to use it on systems where it makes sense to differentiate between a regular QEvent::TouchEnd and abrupt touch sequence cancellations caused by the compositor. For example, when a swype gesture is recognized.

Changes to QFile

Changes to QFont

Changes to QMetaType

  • QMetaType::construct() is renamed as QMetaType::create().
  • QMetaType::unregisterType() is removed.
  • QMetaType now records whether the type argument inherits QObject. Such information can be useful for scripting APIs, so that custom QObject subclasses are treated as QObject pointers. For example, in Qt Script this means QScriptValue::isQObject() can be true, where it was false before.
  • QMetaType::QWidgetStar is removed. Use qMetaTypeId<QWidget*>() or QVariant::canConvert<QWidget*>() instead.
  • Q_DECLARE_METATYPE(type) now requires type to be fully defined. This means, Q_DECLARE_METATYPE(QSharedPointer<t>) and Q_DECLARE_METATYPE(QWeakPointer<t>) also need type to be fully defined. In cases where a forward declared type is needed as a meta-type, use Q_DECLARE_OPAQUE_POINTER(type).

Changes to QMetaMethod

Changes to QObject

Changes to QVariant

  • The QVariant constructor which takes Qt::GlobalColor argument is removed. Code constructing such variants must explicitly call QColor constructor now. For example, instead of QVariant(Qt::red), use QVariant(QColor(Qt::red)) to create a QVariant instance.
  • Implicit creation of QVariant objects from the enum values Qt::BrushStyle, Qt::PenStyle, and Qt::CursorShape has been removed. Create objects explicitly or use static_cast<int>(Qt::SolidLine) to create a QVariant of type int with the same value as the enum.

Changes to QAbstractEventDispatcher

Changes to QDir

Changes to QLocale

Changes to QAbstractItemModel

Changes to QString

Changes to QDate, QTime, and QDateTime

  • QDate only implements the Gregorian calendar, and the switch to the Julian calendar before 1582 has been removed. This means all QDate functions return different results for dates prior to 15 October 1582, and there is no longer a gap between 4 October 1582 and 15 October 1582.
  • QDate::setYMD() is deprecated, use QDate::setDate() instead.
  • Adding days to a null QDate or seconds to a null QTime will no longer return a valid QDate/QTime.
  • The QDate::addDays() and QDateTime::addDays() functions now take a qint64 argument, and the QDate::daysTo() and QDateTime::daysTo() functions now return a qint64 value.
  • QDate and QTime are the userProperty for the QTimeEdit and QDateEdit classes, insted of QDateTime as it was for the 4.7 and 4.8 releases. The USER property for these classes was removed before Qt 4.7.0 and added again in Qt 5.0.
  • The serialization behavior for QDateTime is reverted to pre-Qt 5, because Qt::LocalTime is the local time (that is, ymd hms) regardless of the underlying system time, time zone, or changes in the system zone. Therefore, the consistent behavior when serialising is to save and restore as the local time and not its UTC equivalent. This means that the QDataStream version is 14 since Qt 5.1.
  • The supported date range in QDateTime has been reduced to about +/- 292 million years, the range supported by the number of msecs since the Unix epoch of 1 Jan 1970 as stored in a qint64, and as able to be used in QDateTime::setMSecsSinceEpoch() and QDateTime::toMSecsSinceEpoch().
  • QDate::fromString() and QDateTime::fromString() require non-numeric date component separators when parsing Qt::ISODate. A string like 2000901901 will no longer be recognized as a valid ISO date, whereas 2000/01/01 will, even though it differs from the ISO format 2000-01-01.

Changes to QTextCodec

  • QTextCodec::codecForCStrings() and QTextCodec::setCodecForCStrings() are removed as they were creating uncertainty/bugs in using QString easily and (to a lesser extent) performance issues.
  • QTextCodec::codecForTr() and QTextCodec::setCodecForTr() are removed.

Changes to QUrl

QUrl changed considerably in Qt 5 to comply better with the URL specifications and with brokenness out there. The following list summarizes the most important functional changes:

  • QUrl::setPath() no longer handles relative paths. They are by definition invalid. Use the QUrl::NormalizePathSegments flag to remove /./ or /../ sequences as much as possible. It will not remove /../ from the beginning of the path.
  • QUrl has been changed to operate only on percent-encoded forms. Fully-decoded forms where the percent character stands for itself, can no longer be encoded, as the getters and setters with encoded in the name are deprecated (except QUrl::toEncoded() and QUrl::fromEncoded()).

    The most notable difference with this change is when dealing with QUrl::toString(). In earlier Qt versions, this function would return percent characters in the URL, but now it returns %25 like QUrl::toEncoded() does.

  • QUrl no longer decodes %7B and %7D to "{" and "}" in the output of QUrl::toString().
  • QUrl now defaults to decoded mode in the getters and setters for userName, password, host, topLevelDomain, path and fileName. This means a % in one of those fields is now returned (or set) as % rather than %25. If the former behavior was expected, pass PrettyDecoded to the getter and TolerantMode to the setter.
  • QUrl no longer has functions that handle individual query items and query delimiters, such as addQueryItem() and queryPairDelimiter(). These have been moved to the new QUrlQuery class.
  • QUrl no longer considers all delimiter characters equivalent to their percent-encoded forms. QUrl and QUrlQuery always keep all delimiters exactly as they were in the original URL text.
  • QUrl no longer supports QUrl::FullyDecoded mode in QUrl::authority() and QUrl::userInfo(), nor QUrl::DecodedMode in QUrl::setAuthority() and QUrl::setUserInfo().
  • QUrl no longer decodes %23 found in the fragment to "#" in the output of QUrl::toString (FullyEncoded) or QUrl::toEncoded().

Changes to Qt Concurrent

Qt Concurrent has been moved from Qt Core to its own module. To link against the Qt Core module, add this line to the project file:

 QT += concurrent

Note: The QtConcurrent::Exception class is renamed QException and QtConcurrent::UnhandledException class is renamed QUnhandledException. They remain in Qt Core.

Changes to Qt GUI

Changes to QAccessibleInterface

Changes to QImage

  • QImage::fill() on an image with format Format_RGB888 now expects image data in RGB layout as opposed to BGR layout. This is to ensure consistency with RGB32 and other 32-bit formats.
  • The behavior of QImage::load(), QImage::loadFromData(), QPixmap::load(), and QPixmap::loadFromData() on a non-null image changed so that if the functions fail to load the image (return false), the the existent image data is invalidated, so that isNull() is guaranteed to return true in this case.

Changes to QPainter

  • QPainter does not support uniting clipped regions anymore. Use QRegion::united() instead to unite clips and pass the result to QPainter.
  • QPainter fill rules when not using antialiased painting have changed so that the aliased and antialiased coordinate systems match. There used to be an offset of slightly less than half a pixel when doing sub-pixel rendering, in order to be consistent with the old X11 paint engine. The new behavior should be more predictable and give the same consistent rounding for images and pixmaps as for paths and rectangle filling. To get the old behavior, set the QPainter::Qt4CompatiblePainting render hint.

Changes to QTouchEvent

  • QTouchEvent::DeviceType and QTouchEvent::deviceType() are deprecated as QTouchDevice provides a better way to identify and access the device from which the events originate.
  • The constructor now takes a QTouchDevice pointer instead of DeviceType value.
  • TouchPointStateMask and TouchPointPrimary are removed from the Qt::TouchPointStates enum.
  • QTouchEvent::TouchPoint::isPrimary() is removed.

Changes to Qt Widgets

Changes to QApplication

Changes to QStyle

  • QStyle::standardIconImplementation() and QStyle::layoutSpacingImplementation() are removed, and the QStyle::standardIcon() and QStyle::layoutSpacing() functions are made pure virtual now. The removed functions were introduced in Qt 4 for binary compatibility reasons.
  • QMotifStyle, QPlastiqueStyle, QCleanlooksStyle, and QCDEStyle are replaced with a new fusion style. If your application depends on any of these removed styles, you can either use the qtstyleplugins project to get these styles or update your application to use the new fusion style. For more details about this change, see https://blog.qt.io/blog/2012/10/30/cleaning-up-styles-in-qt5-and-adding-fusion/.
  • The following QStyle implementations have been made internal:
    • QFusionStyle
    • QGtkStyle
    • QMacStyle
    • QWindowsCEStyle
    • QWindowsMobileStyle
    • QWindowsStyle
    • QWindowsVistaStyle
    • QWindowsXPStyle

    Instead of creating instances or inheriting these classes directly, use:

Changes to QHeaderView

The following functions are deprecated:

Changes to QAbstractItemView

  • The derived classes now emit the clicked() signal on the left mouse click only, instead of all mouse clicks.
  • The virtual QAbstractItemView::dataChanged() function signature now includes the roles that have changed. The signature is consistent with the dataChanged() signal in the model.

Changes to QColorDialog

Changes to Qt WebKit

  • The WebKit module in Qt is now split in two modules, webkit and webkitwidgets, in order to allow the dependency of the widgets module to be optional. The benefits will only be available once the QQuickWebView API is made public through C++ in a future version. The webkitwidgets module adds the webkit module automatically to the project, so in your application's project file, QT += webkit should now be modified to:
     QT += webkitwidgets
    
  • The same applies to the module include, #include <QtWebKit/QtWebKit> should be modified to:
     #include <QtWebKitWidgets/QtWebKitWidgets>
    
  • A consequence of the module split is that classes of the Qt WebKit API aren't all in the new module, so for a better compatibility of your application with both Qt4 and Qt5, #include <QtWebKit/QWebPage>, for example, should be included directly as:
     #include <QWebPage>
    

    The include path will take care of selecting the right module.

  • The qwebkitversion.h header has been renamed to qtwebkitversion.h to match other Qt modules, and part of its contents has been moved to qwebkitglobal.h. #include <qwebkitversion.h> should be replaced with two includes:
     #include <qtwebkitversion.h>
     #include <qwebkitglobal.h>
    

Changes to Qt Print Support

  • The QPageSetupDialog::PageSetupDialogOption enum and the corresponding set and get functions, QPageSetupDialog::options() and QPageSetupDialog::setOptions() are removed.
  • Support for printing PostScript files has been removed.
  • The QAbstractPageSetupDialog class is removed. Use QPrintDialog instead.
  • The QPrintEngine::PrintEnginePropertyKey enum value PPK_SuppressSystemPrintStatus is removed.
  • QPrinter no longer allows you to set an invalid printer name.

Changes to Qt Network

Changes to QSslCertificate

Changes to Qt SQL

Changes to Qt Test

  • The plain-text, XML and lightxml test output formats are updated to include test result for every row of test data in data-driven tests. In Qt4, only fails and skips were included for individual data rows without the passes information. This limitation prevented accurate test run and pass rates calculation.
  • The QTRY_VERIFY and QTRY_COMPARE macros are now part of QTestLib. These macros were part of tests/shared/util.h earlier, but now they are part of the <QtTest/QtTest> header. In addition, QTRY_VERIFY_WITH_TIMEOUT and QTRY_COMPARE_WITH_TIMEOUT are provided to specify custom timeout values.
  • The QTEST_NOOP_MAIN macro is removed. If a test appears to be inapplicable for a particular build at compile-time, it should be omitted either using the .pro file logic or call QSKIP in the initTestCase() method to skip the entire test. If you're using the later approach, report a meaningful explanation in the test log.
  • The DEPENDS_ON macro is removed as it misled some users to believe that they could make test functions depend on each other or impose an execution order on test functions.
  • QTest::qt_snprintf() is removed. This was an internal test library function that was exposed in the public API due to its use in a public macro. Any calls to this function must be replaced with QByteArray::qsnprintf().
  • c{QTest::pixmapsAreEqual()} is removed. Comparison of QPixmap objects must be done using the QCOMPARE macro, which provides more informative output in the event of a failure.
  • The "mode" parameter in QSKIP macro is removed. This parameter caused problems in test metrics calculation because of the SkipAll mode, which hid information about the skipped test data. Calling QSKIP in a test function now behaves like SkipSingle, which is skipping a non-data-driven test function or skipping only the current data row of a data-driven test function. Every skipped data row is now reported in the test log.
  • qCompare() has been replaced by overloading. Code such as qCompare<QString>(l, r) no longer uses the QString-specific implementation and may fail to compile. We recommend that you replace specialization with overloading. Also, rather than pass explicit template arguments to qCompare, let the overload resolution pick the correct one, and cast arguments in case of ambiguous overloads (for example, qCompare(QString(l), r)). The resulting code will continue to work against older QtTestlib versions.
  • QTest::qWaitForWindowShown() is replaced with QTest::qWaitForWindowExposed().

Changes to Qt OpenGL

Apart from the QGLWidget class, the Qt OpenGL module should not be used for new code. Instead, use the corresponding OpenGL classes in Qt GUI.

Changes to Qt Global

Changes to Tools

  • The qttest_p4.prf file is removed. Use CONFIG+=testcase and other flags instead.
  • The -dwarf2 configure argument is removed. DWARF2 is always used on macOS now.
  • Configure no longer calls qmake -recursive by default, because the subsequent build invokes qmake as needed. Use -fully-process to restore the old behavior.
  • The lupdate CODECFORTR variable is deprecated, because source code written with Qt 5 is expected to use UTF-8 encoding.