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.

Qt Core 的变化

  • QLibrary::resolve () now returns a function pointer instead of void 指针。
  • QLibraryInfo::buildKey() 和相应 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 (),和 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 () 函数代替。
  • 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 代替。
  • 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 ,和 QAbstractFileEngineHandler are no longer public. We recommend you to avoid using these classes as there is no compatibility promise.
  • qDebug (), qWarning (), qCritical (),和 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 环境变量。 qInstallMsgHandler () is deprecated, so we recommend using qInstallMessageHandler () 代替。
  • 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 ), QPointer was cleared by the QWidget destructor. In Qt 5, the QPointer is cleared by the QObject destructor along with the QWeakPointer s. 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 * 在所有平台。
  • The non-atomic convenience methods of QAtomicInt and QAtomicPointer (that is, operator= , operator int , operator T* , operator! , operator== , operator!= ,和 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() ,和 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 (), 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

Changes to QEvent

  • QEvent::AccessibilityPrepare , QEvent::AccessibilityHelp ,和 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*> () 或 QVariant::canConvert<QWidget*> () 代替。
  • 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

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 () 代替。
  • Adding days to a null QDate or seconds to a null QTime will no longer return a valid QDate / QTime .
  • The QDate::addDays () 和 QDateTime::addDays () functions now take a qint64 argument, and the QDate::daysTo () 和 QDateTime::daysTo () functions now return a qint64 值。
  • QDate and QTime are the userProperty 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 () 和 QDateTime::toMSecsSinceEpoch ().
  • QDate::fromString () 和 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 () 和 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 () 做。

  • 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 % 而不是 %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 类。
  • 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 () 和 QUrl::userInfo (), nor QUrl::DecodedMode in QUrl::setAuthority () 和 QUrl::setUserInfo ().
  • QUrl no longer decodes %23 found in the fragment to "#" in the output of QUrl::toString ( FullyEncoded ) 或 QUrl::toEncoded ().

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
			

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

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.
  • 行为在 QImage::load (), QImage::loadFromData (), QPixmap::load (),和 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 在此情况下。

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 渲染提示。

Changes to QTouchEvent

Qt Widgets 的变化

Changes to QApplication

Changes to QStyle

  • QStyle::standardIconImplementation() and QStyle::layoutSpacingImplementation() are removed, and the QStyle::standardIcon () 和 QStyle::layoutSpacing () functions are made pure virtual now. The removed functions were introduced in Qt 4 for binary compatibility reasons.
  • QMotifStyle , QPlastiqueStyle , QCleanlooksStyle ,和 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/ .
  • 下列 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.
  • 虚拟 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 q t webkitversion.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>
    
    					

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 代替。
  • The QPrintEngine::PrintEnginePropertyKey enum value PPK_SuppressSystemPrintStatus is removed.
  • QPrinter no longer allows you to set an invalid printer name.

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 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() 被替换采用 QTest::qWaitForWindowExposed ().

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.

版权所有  © 2014-2025 乐数软件    

工业和信息化部: 粤ICP备14079481号-1