C++ API changes

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

The following sections lists the API changes in each module and provides recommendations to handle those changes.

Changes to Qt Core

  • The QObject::connectNotify() and QObject::disconnectNotify() functions now need a QMetaMethod argument that identifies the signal, rather than a const char pointer.
  • 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.
  • QCoreApplication::translate() no longer returns the source text if the translation is empty. Use the Qt Linguist Release tool (lrelease -removeidentical) instead for optimization.
  • 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.
  • QString and QByteArray constructors now use a negative size to indicate that the string passed is null-terminated (a null-terminated array of QChar, in the case of QString). In Qt 4, negative sizes were ignored, which resulted in empty QString and QByteArray. The size argument now has a default value of -1, replacing the separate constructors that did the same.
  • QBool is removed. In Qt 4, QString::contains(), QByteArray::contains(), and QList::contains() returns 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.
  • QMetaType has undergone the following changes:
    • 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).
  • QMetaMethod has undergone the following changes:
  • 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.
  • QAbstractEventDispatcher has undergone the following changes:
    • The signature for the pure-virtual registerTimer() function is changed. All subclasses of QAbstractEventDispatcher must re-implement the function with this new signature:
      virtual void registerTimer(int timerId, int interval,Qt::TimerType timerType, QObject *object) = 0;
    • QAbstractEventDispatcher::TimerInfo is no longer a typedef of QPair<int, int>. It is now a struct with 3 members: int timerId, int interval, and Qt::TimerType timerType. Update the QAbstractEventDispatcher::registeredTimers function with this change.
  • 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 creates a console.
  • QDir has undergone the following changes:
  • 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.
  • The QLocale::toShort(), QLocale::toUShort(), QLocale::toInt(), QLocale::toUInt(), QLocale::toLongLong(), and QLocale::toULongLong() functions no longer take the argument for base. They localize base 10 conversions. To convert other bases, use the QString functions instead.
  • QSystemLocale is not public anymore. Use QLocale instead.
  • The QChar::NoCategory enum value is removed. The QChar::Other_NotAssigned enum value is returned for unassigned codepoints now.
  • QAbstractItemModel has undergone the following changes:
    • beginMoveRows() no longer emits the layoutAboutToBeChanged signal, and endMoveRows() no longer emits the layoutChanged signal. All proxy models must connect to (and disconnect from) the rowsAboutToBeMoved and rowsMoved signals.
    • QAbstractItemModel::sibling() is virtual now to allow implementations to optimize based on internal data.
    • QAbstractItemModel::createIndex() method now only provides the void* and quintptr overloads, making calls with a literal 0 (createIndex(row, col, 0)) ambiguous. Either cast (quintptr(0)) or omit the third argument(to get the void* overload).
  • QAbstractItemModel::setRoleNames() is deprecated. Use QAbstractItemModel::roleNames() instead. QAbstractItemModel::roleNames() is virtual now to allow a consistent API with the rest of QAbstractItemModel. Reimplementing the virtual methods to provide the elements is preferred to setting those directly.
  • Default value of the QSortFilterProxyModel::dynamicSortFilter property is changed to true.
  • QString::mid(), QString::midRef(), and QByteArray::mid() now return an empty QString, QStringRef, and QByteArray respectively, if the position passed is equal to the length (that is, right after the last character/byte). In Qt 4, they use to return a null QString or a null QStringRef.
  • The following QString functions use the C locale instead of the default or system locale:

    This is to guarantee consistent default conversion of strings. For locale-aware conversions use the equivalent QLocale functions.

  • QDate, QTime, and QDateTime has undergone the following important behavioral changes:
    • 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 takes a qint64 argument, and the QDate::daysTo() and QDateTime::daysTo() functions now returns a qint64 value.
  • QTextCodec has undergone the following changes:
    • 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.
  • QObject::trUtf8() and QCoreApplication::Encoding are deprecated. Qt assumes that the source code is encoded in UTF-8.
  • QFile::setEncodingFunction() and QFile::setDecodingFunction() are deprecated. The QFile::encodeName() and QFile::decodeName() functions are now hard-coded to operate on QString::fromLocal8Bit() and QString::toLocal8Bit() only. The old behavior is still possible using QTextCodec::setCodecForLocale(), but it is recommended that the new code should not make assumptions about the file system encoding and older code should remove such assumptions.
  • QEvent::AccessibilityPrepare, {QEvent::AccessibilityHelp}, and QEvent::AccessibilityDescription are removed.
  • 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.

  • 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 version, 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 QPointers tracking a widget is not cleared before the QWidget destructor destroys the children for the widget being tracked.
  • 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 version, this function would return percent characters in the URL, but now it returns "%25" like the QUrl::toEncoded() does.

  • 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.
  • Qt::WFlags(obsolete) 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.

Changes to Qt GUI

  • QPainter does not support uniting clipped regions anymore. Use QRegion::united() instead to unite clips and pass the result to QPainter.
  • QPen now has a default width of 1 instead of 0. Thus, it is no longer cosmetic by default.
  • QAccessibleInterface has undergone the following changes:
    • The "child" integer parameters are removed to bring it more closer to IAccessible2, and this means the following functions lose the integer parameter:
    • navigate() is replaced with parent() and child() to navigate the hierarchy.
    • relationTo() is replaced with relations().
    • QAccessibleInterface::userActionCount(), QAccessibleInterface::actionText(), and QAccessibleInterface::doAction() are removed. We recommend the QAccessibleInterface subclasses to implement the QAccessibleActionInterface instead.
  • The constructor of QAccessibleEvent does not need the child parameter anymore, and the corresponding QAccessibleEvent::child() function is removed.
  • The constructor of QTabletEvent does not need the hiResGlobalPos argument anymore, as all coordinates are floating point-based now.
  • QTouchEvent has undergone the following changes:
    • The DeviceType(obsolete) enum and QTouchEvent::deviceType{deviceType()} function 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.
    • QTouchEvent::TouchPoint::isPrimary() is removed.
    • QWidget *widget() is replaced with QObject *target() to avoid QWidget dependencies.
    • 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.
  • QIconEngineV2 is now merged into QIconEngine. Update your sources to use QIconEngine instead of QIconEngineV2.
  • QSound is moved to Qt Multimedia from Qt GUI.
  • 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.
  • QDesktopServices::storageLocation() and QDesktopServices::displayName() are replaced by QStandardPaths::writableLocation() and QStandardPaths::displayName() respectively. They are now in the Qt Core module. Make sure to read the QDesktopServices::storageLocation() documentation when porting from QDesktopServices::DataLocation(obsolete).
  • QPixmap::grabWindow() and QPixmap::grabWidget() are removed. Use QScreen::grabWindow() instead.
  • QMotifStyle, QPlastiqueStyle, QCleanlooksStyle, and QCDEStyle are replaced with a new style, QFusionStyle. 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.digia.com/blog/2012/10/30/cleaning-up-styles-in-qt5-and-adding-fusion/.

Changes to Qt Widgets

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 profitable once the QQuickWebView API are 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.

Changes to Qt Network

Changes to Qt SQL

Changes to Qt Test

The following source incompatible changes are made in this module:

  • 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.
  • The QTest::qt_snprintf() function 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().
  • The QTest::pixmapsAreEqual() function 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.
  • QTest::qWaitForWindowShown() is replaced with QTest::qWaitForWindowExposed().

Changes to Qt Global

The following source incompatible changes are made:

  • qMacVersion(): This global function is removed. Use QSysInfo::macVersion() or QSysInfo::MacintoshVersion instead.
  • Qt::escape(): This global function is deprecated. Use QString::toHtmlEscaped() instead.
  • qIsDetached<>: This global function is removed as it is not relevant anymore for multi-threaded applications. There is no replacement for this function.

Changes to Tools

  • Avoid using qttest_p4.prf file. We recommend that you explicitly enable the preferences you want. Autotest .pro files must stop using 'load(qttest_p4)' and use 'CONFIG+=testcase' instead.
  • The -dwarf2 configure argument is removed. DWARF2 is always used on Mac OS X now.

Related Topics

Notes provided by the Qt Community

No notes