Difference between revisions of "Transition from Qt 4.x to Qt5"

From Qt Wiki
Jump to: navigation, search
 
 
(15 intermediate revisions by 11 users not shown)
Line 1: Line 1:
=The Transition from Qt 4.x to Qt 5=
+
{{LangSwitch}}
  
The transition from Qt 4.x to Qt 5 is not expected to be significant. However, the “modularization” of the Qt code base requires some amount of changes to project configuration, such as use of “headers”, and configuration of project build settings (such as changes to the *.pro files).
+
[[Category:Developing_with_Qt]]
 +
[[Category:Developing_Qt]]
  
Qt Creator (master) is compiled using Qt 4 and Qt 5; you can refer to its sources to get an overview of what is required to port an application and keep the sources backwards compatible to Qt 4.
+
The transition from Qt 4.x to Qt 5 is not expected to be significant. However, the "modularization" of the Qt code base requires some amount of changes to project configuration, such as use of "headers", and configuration of project build settings (such as changes to the *.pro files).
  
==QtWidgets as a Separate Module==
+
== QtWidgets as a Separate Module ==
  
===example compile time errors===
+
=== example compile time errors ===
 +
<code>
 +
error: QMainWindow: No such file or directory
 +
error: QToolButton: No such file or directory
 +
error: QWidget: No such file or directory
 +
</code>
  
===Solution===
+
=== Solution ===
  
 
Add this in your *.pro file:
 
Add this in your *.pro file:
 +
 +
<code>
 +
QT += widgets
 +
</code>
  
 
Change all instances of
 
Change all instances of
 +
 +
<code>
 +
#include <QtGui>
 +
</code>
  
 
to
 
to
 +
 +
<code>
 +
#include <QtWidgets>
 +
</code>
  
 
The code should work now, though sometimes you may require to be more explicit:
 
The code should work now, though sometimes you may require to be more explicit:
  
==QtWebKitWidgets is also a separate module:==
+
<code>
 +
#include <QtWidgets/QToolButton>
 +
</code>
 +
 
 +
== QtWebKitWidgets is also a separate module: ==
  
===example compile time errors===
+
=== example compile time errors ===
 +
<code>
 +
error: invalid use of incomplete type 'class QWebFrame'
 +
error: forward declaration of 'class QWebFrame'
 +
</code>
  
===Solution===
+
=== Solution ===
  
 
Add this in your *.pro file:
 
Add this in your *.pro file:
  
'''Note''': when you have QT += webkitwidgets you don’t need QT += widgets
+
<code>
 +
QT += webkitwidgets
 +
</code>
 +
 
 +
'''Note''': when you have QT += webkitwidgets you don't need QT += widgets
  
 
In addition, replace all instances of
 
In addition, replace all instances of
 +
 +
<code>
 +
#include <QtWebKit>
 +
</code>
  
 
to
 
to
  
You can try this by porting a [http://qt.gitorious.org/qt-labs/graphics-dojo/trees/c8d0c381b994d7417863832929cc4c3f710f2db5/htmleditor <span class="caps">WYSISWYG</span> html editor] ''[qt.gitorious.org]'' from Qt 4 to Qt 5.
+
<code>
 +
#include <QtWebKitWidgets>
 +
</code>
 +
 
 +
You can try this by porting a [http://qt.gitorious.org/qt-labs/graphics-dojo/trees/c8d0c381b994d7417863832929cc4c3f710f2db5/htmleditor WYSISWYG html editor] from Qt 4 to Qt 5.
  
==QPrinter Doesn’t Work==
+
== QPrinter Doesn't Work ==
  
 
If your code has the following lines:
 
If your code has the following lines:
 +
 +
<code>
 +
#include <QPrinter>
 +
#include <QPrintDialog>
 +
</code>
  
 
add the following to your project file:
 
add the following to your project file:
 +
 +
<code>
 +
QT += printsupport
 +
</code>
  
 
Again, sometimes it may not work and you would need to be explicit:
 
Again, sometimes it may not work and you would need to be explicit:
  
==toAscii() and fromAscii() Methods are deprecated==
+
<code>
 +
#include <QtPrintSupport/QPrinter>
 +
#include <QtPrintSupport/QPrintDialog>
 +
</code>
 +
 
 +
== toAscii() and fromAscii() Methods are deprecated ==
 +
 
 +
Replace all instances of
  
Replace all instances of
+
<code>
 +
fromAscii()
 +
toAscii()
 +
</code>
  
to <br />
+
to
 +
<code>
 +
fromLatin1()
 +
toLatin1()
 +
</code>
  
For example, given the Qt 4 code<br />
+
For example, given the Qt 4 code
 +
<code>
 +
QByteArray configfileti = TMP_Config.toAscii();
 +
</code>
  
you would change to <br />
+
you would change to
 +
<code>
 +
QByteArray configfileti = TMP_Config.toLatin1();
 +
</code>
  
==QCoreApplication::UnicodeUTF8 is deprecated==
+
== QCoreApplication::UnicodeUTF8 is deprecated ==
  
This enum type used to define the 8-bit encoding of character string arguments to translate(). This enum is now obsolete and <span class="caps">UTF</span>-8 will be used in all cases. So remove all instances of QCoreApplication::UnicodeUTF8. For example:
+
This enum type used to define the 8-bit encoding of character string arguments to translate(). This enum is now obsolete and UTF-8 will be used in all cases. So remove all instances of QCoreApplication::UnicodeUTF8. For example:
 +
 
 +
<code>
 +
Href_Gui->setWindowTitle(QApplication::translate("Href_Gui", "Url / www", 0, QApplication::UnicodeUTF8));
 +
label->setText(QApplication::translate("Href_Gui", "Text:", 0, QApplication::UnicodeUTF8));
 +
label_2->setText(QApplication::translate("Href_Gui", "Url:", 0, QApplication::UnicodeUTF8));
 +
label_3->setText(QApplication::translate("Href_Gui", "Target / Name:", 0, QApplication::UnicodeUTF8));
 +
</code>
  
 
to
 
to
  
==QWorkspace is deprecated==
+
<code>
 +
Href_Gui->setWindowTitle(QApplication::translate("Href_Gui", "Url / www", 0));
 +
label->setText(QApplication::translate("Href_Gui", "Text:", 0));
 +
label_2->setText(QApplication::translate("Href_Gui", "Url:", 0));
 +
label_3->setText(QApplication::translate("Href_Gui", "Target / Name:", 0));
 +
</code>
  
This class is obsolete and was replaced by the QMdiArea class in Qt 4.3. In Qt 5 QWorkspace has been removed. The new class has a similar <span class="caps">API</span> to QWorkspace and porting it only involved changing the names of a few methods, signals, and slots.
+
== QWorkspace is deprecated ==
 +
 
 +
This class is obsolete and was replaced by the QMdiArea class in Qt 4.3. In Qt 5 QWorkspace has been removed. The new class has a similar API to QWorkspace and porting it only involved changing the names of a few methods, signals, and slots.  
  
 
replace
 
replace
 +
 +
<code>#include <QWorkspace>
 +
</code>
  
 
with
 
with
  
==QDrag Problems==
+
<code>#include <QMdiArea>
 +
</code>
  
Apps that has drop and drag functionality will need some tweaking. A line such as
+
== QDrag Problems ==
 +
 
 +
Apps that have drop and drag functionality will need some tweaking. A line such as
 +
 
 +
<code>
 +
QDrag *drag = new QDrag(event->widget());
 +
</code>
  
 
in Qt 5 will generate the error
 
in Qt 5 will generate the error
 +
 +
<code>
 +
error: no matching function for call to 'QDrag::QDrag(QWidget*)'
 +
</code>
  
 
To fix this add among the includes:
 
To fix this add among the includes:
  
==qFindChildren is deprecated==
+
<code>
 +
#include <QWidget>
 +
</code>
  
An error will pop of this fashion:<br />
+
== qFindChildren is deprecated ==
 +
 
 +
An error will pop of this fashion:
 +
<code>
 +
error: 'qFindChildren' was not declared in this scope
 +
</code>
  
 
To solve this you replace qFindChildren with findChildren, for example in
 
To solve this you replace qFindChildren with findChildren, for example in
 +
 +
<code>
 +
toString(const QObject* obj, int indentLevel) const {
 +
[…]
 +
/* Query over QObjects */
 +
if (m_children) {
 +
QList<QObject*> childlist = qFindChildren<QObject*>(obj, QString());
 +
[…]
 +
</code>
  
 
replace
 
replace
 +
 +
<code>
 +
QList<QObject*> childlist = qFindChildren<QObject*>(obj, QString());
 +
</code>
  
 
with
 
with
  
[https://bugs.webkit.org/attachment.cgi?id=82025&action=diff source] ''[bugs.webkit.org]''
+
<code>
 +
QList<QObject*> childlist = obj->findChildren<QObject*>(QString());
 +
</code>
 +
 
 +
 
 +
[https://bugs.webkit.org/attachment.cgi?id=82025&action=diff source]
 +
 
 +
== qInstallMsgHandler is deprecated ==
 +
 
 +
The 4.8 function [http://doc.qt.io/archives/qt-4.8/qtglobal.html#qInstallMsgHandler qInstallMsgHandler] has been replaced with [http://doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler qInstallMessageHandler]. The functions are similar, but the function signature of the `handler` has also changed, adding a very useful [http://doc.qt.io/qt-5/qmessagelogcontext.html QMessageLogContext] and replacing the char array with a QString reference.
  
==qVariantValue is deprecated==
+
Your compiler will complain
  
Your compiler will say<br />
+
<code>
 +
error: 'qInstallMsgHandler': identifier not found
 +
</code>
  
This function is equivalent to QVariant::value&lt;T&gt;(value). Therefore if given a QVariant val rewrite the line<br />
+
so replace
 +
 
 +
<code>
 +
void myhandler(QtMsgType type, const char* msg) {
 +
    switch (type) {
 +
    case QtDebugMsg:
 +
        fprintf(stderr, "Debug: %s\n", msg);
 +
        break;
 +
    case QtWarningMsg:
 +
        fprintf(stderr, "Warning: %s\n", msg);
 +
        break;
 +
    case QtCriticalMsg:
 +
        fprintf(stderr, "Critical: %s\n", msg);
 +
        break;
 +
    case QtFatalMsg:
 +
        fprintf(stderr, "Fatal: %s\n", msg);
 +
        abort();
 +
    }
 +
}
 +
 
 +
int main(int argc, char** argv) {
 +
    qInstallMsgHandler(myhandler);
 +
    QApplication app(argc, argv);
 +
    //...
 +
    return app.exec();
 +
}
 +
</code>
 +
 
 +
with
 +
 
 +
<code>
 +
void myhandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { //<-- new signature! added context!
 +
    QByteArray localMsg(msg.toLocal8Bit());      //<-- not a char* any more!
 +
    switch (type) {
 +
    case QtDebugMsg:
 +
        fprintf(stderr, "Debug: %s (%s:%u, %s)\n",    localMsg.constData(), context.file, context.line, context.function);
 +
        break;
 +
    case QtInfoMsg:
 +
        fprintf(stderr, "Info: %s (%s:%u, %s)\n",    localMsg.constData(), context.file, context.line, context.function);
 +
        break;
 +
    case QtWarningMsg:
 +
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n",  localMsg.constData(), context.file, context.line, context.function);
 +
        break;
 +
    case QtCriticalMsg:
 +
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
 +
        break;
 +
    case QtFatalMsg:
 +
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n",    localMsg.constData(), context.file, context.line, context.function);
 +
        break;                                  //<-- Qt example doesn't abort() any more with fatal error
 +
    }
 +
}
 +
 
 +
int main(int argc, char** argv) {
 +
    qInstallMessageHandler(myhandler);          //<-- new function
 +
    QApplication app(argc, argv);
 +
    //...
 +
    return app.exec();
 +
}
 +
</code>
 +
 
 +
== qVariantValue is deprecated ==
 +
 
 +
Your compiler will say
 +
<code>
 +
error: 'qVariantValue' was not declared in this scope
 +
</code>
 +
 
 +
This function is equivalent to QVariant::value<T>(value). Therefore if given a QVariant val rewrite the line
 +
<code>
 +
QTime t = qVariantValue<QTime>(val);
 +
</code>
  
 
to
 
to
 +
 +
<code>
 +
QTime t = val.value<QTime>();
 +
</code>
  
 
This QTime enclosed in the angled brackets lets the compiler know what QVariant will return. However, if the variable is not a QVariable the type enclosed in the angled brackets should not be used(doing so will result in a vague compile time error). So given that m_color is of type QColor you will rewrite
 
This QTime enclosed in the angled brackets lets the compiler know what QVariant will return. However, if the variable is not a QVariable the type enclosed in the angled brackets should not be used(doing so will result in a vague compile time error). So given that m_color is of type QColor you will rewrite
 +
 +
<code>
 +
s.setValue("color/favorite", qVariantValue<QColor>(m_color));
 +
</code>
  
 
to
 
to
  
[http://stackoverflow.com/questions/14919867/qvariantvalue-is-qt-deprecated-what-is-the-replacement source] ''[stackoverflow.com]''
+
<code>
 +
s.setValue("color/favorite", m_color.value());
 +
</code>
 +
 
 +
[http://stackoverflow.com/questions/14919867/qvariantvalue-is-qt-deprecated-what-is-the-replacement source]
 +
 
 +
== qVariantCanConvert is deprecated ==
  
==qVariantCanConvert is deprecated==
+
replace
  
replace
+
<code>
 +
Q_ASSERT(qVariantCanConvert<QString>(variant));
 +
Q_ASSERT(qVariantCanConvert<QSize>(variant));
 +
Q_ASSERT(qVariantCanConvert<QFont>(fontVariant));
 +
</code>
  
 
with
 
with
  
==Qt::escape is deprecated==
+
<code>
 +
Q_ASSERT(variant.canConvert(QMetaType::QString));
 +
Q_ASSERT(variant.canConvert(QMetaType::QSize));
 +
Q_ASSERT(fontVariant.canConvert(QMetaType::QFont));
 +
</code>
 +
 
 +
== Qt::escape is deprecated ==
 +
 
 +
<code>
 +
error: 'escape' is not a member of 'Qt'
 +
</code>
  
 
So you would change the following block:
 
So you would change the following block:
 +
 +
<code>
 +
if (result == QString())
 +
    result = Qt::escape(val.toString());
 +
else
 +
    result = Qt::escape(result);
 +
return result;
 +
</code>
  
 
to
 
to
  
this procedure can be automated by a [http://www.kdab.com/automated-porting-from-qt-4-to-qt-5/ porting tool] ''[kdab.com]'' from <span class="caps">KDAB</span>.
+
<code>
 +
if (result == QString())
 +
    result = QString(val.toString()).toHtmlEscaped();
 +
else
 +
    result = QString(result).toHtmlEscaped();
 +
return result;
 +
</code>
 +
 
 +
this procedure can be automated by a [http://www.kdab.com/automated-porting-from-qt-4-to-qt-5/ porting tool] from KDAB.
 +
 
 +
== QDesktopServices::storageLocation deprecated ==
  
==QDesktopServices::storageLocation deprecated==
+
<code>
 +
error: 'storageLocation' is not a member of 'QDesktopServices'
 +
error: 'DataLocation' is not a member of 'QDesktopServices'
 +
</code>
  
 
Use QStandardPaths::StandardLocation:
 
Use QStandardPaths::StandardLocation:
 +
 +
<code>
 +
QString path = s.value("db.path", QDesktopServices::storageLocation(QDesktopServices::DataLocation)).toString();
 +
</code>
  
 
to
 
to
  
[http://doc.qt.io/qt-5.0/qtgui/qdesktopservices-obsolete.html source] ''[qt.io]''
+
<code>
 +
QString path = s.value("db.path", QStandardPaths::standardLocations(QStandardPaths::DataLocation)).toString();
 +
</code>
 +
 
 +
[http://doc.qt.io/qt-5/QDesktopServices.html source]
  
==<span class="caps">CONFIG</span>+=qtestlib is deprecated==
+
== CONFIG+=qtestlib is deprecated ==
  
 
If you have the above line in your project file the compiler will warn you in the compile window, nonetheless the code will still run as usual:
 
If you have the above line in your project file the compiler will warn you in the compile window, nonetheless the code will still run as usual:
  
==QWeakPointer quirks==
+
<code>
 +
Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.
 +
</code>
 +
 
 +
== QWeakPointer quirks ==
  
 
A code block like
 
A code block like
 +
 +
<code>
 +
quint64 decodedPointer = line.toULongLong();
 +
MetaData* md = reinterpret_cast<MetaData*>(decodedPointer);
 +
QWeakPointer<MetaData> wp(md);
 +
</code>
  
 
results in
 
results in
 +
 +
<code>
 +
error: no matching function for call to 'QWeakPointer<MetaData>::QWeakPointer(MetaData*&)'
 +
</code>
  
 
To fix this add to the project file:
 
To fix this add to the project file:
  
[http://forum.qt.io/viewthread/27510 source] ''[qt.io]''
+
<code>
 +
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
 +
</code>
 +
 
 +
[http://forum.qt.io/viewthread/27510 source]
 +
 
 +
== QtConcurrent Library is Missing? ==
 +
 
 +
<code>
 +
C:\Qt\5.0.2\5.0.2\mingw47_32\include\QtConcurrent\qtconcurrentthreadengine.h:133: error: undefined reference to
 +
`_imp___ZN12QtConcurrent16ThreadEngineBaseD2Ev'
 +
</code>
  
==QtConcurrent Library is Missing?==
+
In Qt 4, QtConcurrent was part of QtCore, so there was no need to include specific headers. This is no longer the case with Qt 5. If your source code has lines like
  
In Qt 4, QtConcurrent was part of QtCore, so there was no need to include specific headers. This is no longer the case with Qt 5. If your source code have lines like
+
<code>
 +
m_current = QtConcurrent::blockingMappedReduced(slices, functor, stitchReduce, QtConcurrent::UnorderedReduce );
 +
</code>
  
 
You will need to include the header:
 
You will need to include the header:
 +
 +
<code>
 +
#include <QtConcurrent/QtConcurrent>
 +
</code>
  
 
and add the following line to your project file:
 
and add the following line to your project file:
  
==Fixing #include&lt;&gt; Headers==
+
<code>
 +
QT+= concurrent
 +
</code>
  
A Perl script “fixqt4headers.pl” exists in qtbase/bin/. that should be run on source code using Qt that corrects the #include&lt;&gt; directives for Qt components to also consider the module name.
+
== Fixing #include<> Headers ==
  
==Plugin loading==
+
A Perl script "fixqt4headers.pl" exists in qtbase/bin/. that should be run on source code using Qt that corrects the #include<> directives for Qt components to also consider the module name.
  
The Q_EXPORT_PLUGIN,Q_EXPORT_PLUGIN2 macros have been deprecated in favor of the new Q_PLUGIN_METADATA macro. The advantage of the new system is that it allows Qt to query the metadata for the plugin without actually dlopen’ing it. This greatly improves performance and reliability of the plugin system.
+
== Plugin loading ==
  
The new Q_PLUGIN_METADATA macro is included next to the Q_OBJECT macro in the QObject derived class that is returned when loading the plugin. It contains the plugins <span class="caps">IID</span> and a filename pointing to a json file containing the metadata for the plugin. The json file is compiled into the plugin and does not need to be installed.
+
The Q_EXPORT_PLUGIN,Q_EXPORT_PLUGIN2 macros have been deprecated in favor of the new Q_PLUGIN_METADATA macro. The advantage of the new system is that it allows Qt to query the metadata for the plugin without actually dlopen'ing it. This greatly improves performance and reliability of the plugin system.
  
An example on how to change your plugins can be found by looking at the patch that changes the Gif image format plugin, see http://qt.gitorious.org/qt/qtbase/commit/963b4c1647299fd023ddbe7c4a25ac404e303c5d .
+
The new Q_PLUGIN_METADATA macro is included next to the Q_OBJECT macro in the QObject derived class that is returned when loading the plugin. It contains the plugins IID and a filename pointing to a json file containing the metadata for the plugin. The json file is compiled into the plugin and does not need to be installed.
  
==Deploying to systems without C++11==
+
An example on how to change your plugins can be found by looking at the patch that changes the Gif image format plugin, see http://code.qt.io/cgit/qt/qtbase.git/commit/?id=963b4c1647299fd023ddbe7c4a25ac404e303c5d
  
When Qt is built from source code on a system with C++11 installed, the Qt libraries/frameworks are linked against the system’s C++11 library (libc++). This means that the Qt libraries/frameworks are not deployable to systems without C++11 installed (such as out-of-the-box Mac OS X 10.6). To be able to deploy to systems that only support the older C++ standard (libstdc++), build Qt from source code with the -no-c++11 configure option.
+
== Deploying to systems without C++11 ==
  
==QTimer is no longer accurate to the millisecond by default==
+
When Qt is built from source code on a system with C++11 installed, the Qt libraries/frameworks are linked against the system's C++11 library (libc). This means that the Qt libraries/frameworks are not deployable to systems without C++11 installed (such as out-of-the-box Mac OS X 10.6). To be able to deploy to systems that only support the older C++ standard (libstdc++), build Qt from source code with the -no-c++11 configure option.
 +
 
 +
== QTimer is no longer accurate to the millisecond by default ==
  
 
QTimer has now 3 accuracy types, with a new default behaviour:
 
QTimer has now 3 accuracy types, with a new default behaviour:
 
 
* The new default type is Qt::CoarseTimer which, to reduce power/CPU consumption, allow ''5% difference'' between requested time and actual one, and even ''allow the timer to fire before'' the requested time.
 
* The new default type is Qt::CoarseTimer which, to reduce power/CPU consumption, allow ''5% difference'' between requested time and actual one, and even ''allow the timer to fire before'' the requested time.
 
* The former one is Qt::PreciseTimer (to the millisecond, never before the requested time).
 
* The former one is Qt::PreciseTimer (to the millisecond, never before the requested time).
 
* A third one is Qt::VeryCoarseTimer and allow a 1 second difference
 
* A third one is Qt::VeryCoarseTimer and allow a 1 second difference
  
==QUrl addQueryItem moved to QUrlQuery==
+
== QUrl addQueryItem moved to QUrlQuery ==
 +
 
 +
If you have:
 +
<code>
 +
QUrl url;
 +
// …
 +
url.addQueryItem(key, value);
 +
</code>
 +
 
 +
You will want to change it to
 +
<code>
 +
QUrl url;
 +
QUrlQuery urlQuery(url);        //initialize with url to append to existing query, if present
 +
// …
 +
urlQuery.addQueryItem(key, value);
  
If you have:<br />
+
url.setUrlQuery(urlQuery);
 +
</code>
  
You will want to change it to<br />
+
The same applies to the QUrl::getQueryItem() methods. They have been moved to QUrlQuery.
  
==QAbstractItemModel changes==
+
== QAbstractItemModel changes ==
  
both have changed and are now protected.
+
<code>
 +
void reset()
 +
void setRoleNames(const QHash<int, QByteArray> & roleNames)
 +
</code>
 +
both have changed and are now obsolete.
  
See [http://doc.qt.io/qt-5/qabstractitemmodel-compat.html#reset Compatibility Members for QAbstractItemModel] ''[qt.io]''
+
See [http://doc.qt.io/qt-5/qabstractitemmodel-obsolete.html Obsolete Members for QAbstractItemModel]
  
==Recommended Reading==
+
== QHeaderView changes ==
  
* [http://doc.qt.io/qt-5.0/qtdoc/sourcebreaks.html C++ <span class="caps">API</span> Changes] ''[qt.io]''
+
Use <code>void QHeaderView::setSectionResizeMode(QHeaderView::ResizeMode mode)</code> instead of <code>void QHeaderView::setResizeMode(ResizeMode mode)</code> The latter has been removed.
* [http://doc.qt.io/qt-5.0/qtdoc/portingguide.html The porting guide] ''[qt.io]''
 
* [http://blog.ics.com/2013/01/porting-desktop-applications-from-qt-4-to-qt-5.html#.UVDeLReGqSr Porting Desktop Applications from Qt 4 to Qt 5] ''[blog.ics.com]''
 
* [http://www.kdab.com/porting-from-qt-4-to-qt-5/ Porting from Qt 4 to Qt 5] ''[kdab.com]''
 
* [http://www.kdab.com/automated-porting-from-qt-4-to-qt-5/ Automated porting from Qt 4 to Qt 5] ''[kdab.com]''
 
  
===Categories:===
+
== Recommended Reading ==
  
* [[:Category:Developing Qt|Developing_Qt]]
+
* [http://doc.qt.io/qt-5/sourcebreaks.html C++ API Changes]
* [[:Category:Developing with Qt|Developing_with_Qt]]
+
* [http://doc.qt.io/qt-5/portingguide.html The porting guide]
 +
* [http://www.ics.com/blog/porting-desktop-applications-qt-4-qt-5 Porting Desktop Applications from Qt 4 to Qt 5]
 +
* [http://www.kdab.com/porting-from-qt-4-to-qt-5/ Porting from Qt 4 to Qt 5]
 +
* [http://www.kdab.com/automated-porting-from-qt-4-to-qt-5/ Automated porting from Qt 4 to Qt 5]

Latest revision as of 10:36, 12 July 2019

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

The transition from Qt 4.x to Qt 5 is not expected to be significant. However, the "modularization" of the Qt code base requires some amount of changes to project configuration, such as use of "headers", and configuration of project build settings (such as changes to the *.pro files).

QtWidgets as a Separate Module

example compile time errors

error: QMainWindow: No such file or directory
error: QToolButton: No such file or directory
error: QWidget: No such file or directory

Solution

Add this in your *.pro file:

QT += widgets

Change all instances of

#include <QtGui>

to

#include <QtWidgets>

The code should work now, though sometimes you may require to be more explicit:

#include <QtWidgets/QToolButton>

QtWebKitWidgets is also a separate module:

example compile time errors

error: invalid use of incomplete type 'class QWebFrame'
error: forward declaration of 'class QWebFrame'

Solution

Add this in your *.pro file:

QT += webkitwidgets

Note: when you have QT += webkitwidgets you don't need QT += widgets

In addition, replace all instances of

#include <QtWebKit>

to

#include <QtWebKitWidgets>

You can try this by porting a WYSISWYG html editor from Qt 4 to Qt 5.

QPrinter Doesn't Work

If your code has the following lines:

#include <QPrinter>
#include <QPrintDialog>

add the following to your project file:

QT += printsupport

Again, sometimes it may not work and you would need to be explicit:

#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintDialog>

toAscii() and fromAscii() Methods are deprecated

Replace all instances of

fromAscii()
toAscii()

to

fromLatin1()
toLatin1()

For example, given the Qt 4 code

QByteArray configfileti = TMP_Config.toAscii();

you would change to

QByteArray configfileti = TMP_Config.toLatin1();

QCoreApplication::UnicodeUTF8 is deprecated

This enum type used to define the 8-bit encoding of character string arguments to translate(). This enum is now obsolete and UTF-8 will be used in all cases. So remove all instances of QCoreApplication::UnicodeUTF8. For example:

Href_Gui->setWindowTitle(QApplication::translate("Href_Gui", "Url / www", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("Href_Gui", "Text:", 0, QApplication::UnicodeUTF8));
label_2->setText(QApplication::translate("Href_Gui", "Url:", 0, QApplication::UnicodeUTF8));
label_3->setText(QApplication::translate("Href_Gui", "Target / Name:", 0, QApplication::UnicodeUTF8));

to

Href_Gui->setWindowTitle(QApplication::translate("Href_Gui", "Url / www", 0));
label->setText(QApplication::translate("Href_Gui", "Text:", 0));
label_2->setText(QApplication::translate("Href_Gui", "Url:", 0));
label_3->setText(QApplication::translate("Href_Gui", "Target / Name:", 0));

QWorkspace is deprecated

This class is obsolete and was replaced by the QMdiArea class in Qt 4.3. In Qt 5 QWorkspace has been removed. The new class has a similar API to QWorkspace and porting it only involved changing the names of a few methods, signals, and slots.

replace

#include <QWorkspace>

with

#include <QMdiArea>

QDrag Problems

Apps that have drop and drag functionality will need some tweaking. A line such as

QDrag *drag = new QDrag(event->widget());

in Qt 5 will generate the error

error: no matching function for call to 'QDrag::QDrag(QWidget*)'

To fix this add among the includes:

#include <QWidget>

qFindChildren is deprecated

An error will pop of this fashion:

error: 'qFindChildren' was not declared in this scope

To solve this you replace qFindChildren with findChildren, for example in

toString(const QObject* obj, int indentLevel) const {
[]
 /* Query over QObjects */
 if (m_children) {
 QList<QObject*> childlist = qFindChildren<QObject*>(obj, QString());
[]

replace

QList<QObject*> childlist = qFindChildren<QObject*>(obj, QString());

with

QList<QObject*> childlist = obj->findChildren<QObject*>(QString());


source

qInstallMsgHandler is deprecated

The 4.8 function qInstallMsgHandler has been replaced with qInstallMessageHandler. The functions are similar, but the function signature of the `handler` has also changed, adding a very useful QMessageLogContext and replacing the char array with a QString reference.

Your compiler will complain

error: 'qInstallMsgHandler': identifier not found

so replace

void myhandler(QtMsgType type, const char* msg) {
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s\n", msg);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s\n", msg);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s\n", msg);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s\n", msg);
        abort();
    }
}

int main(int argc, char** argv) {
    qInstallMsgHandler(myhandler);
    QApplication app(argc, argv);
    //...
    return app.exec();
}

with

void myhandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { //<-- new signature! added context!
    QByteArray localMsg(msg.toLocal8Bit());       //<-- not a char* any more!
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s (%s:%u, %s)\n",    localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)\n",     localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n",  localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n",    localMsg.constData(), context.file, context.line, context.function);
        break;                                   //<-- Qt example doesn't abort() any more with fatal error
    }
}

int main(int argc, char** argv) {
    qInstallMessageHandler(myhandler);          //<-- new function
    QApplication app(argc, argv);
    //...
    return app.exec();
}

qVariantValue is deprecated

Your compiler will say

error: 'qVariantValue' was not declared in this scope

This function is equivalent to QVariant::value<T>(value). Therefore if given a QVariant val rewrite the line

QTime t = qVariantValue<QTime>(val);

to

QTime t = val.value<QTime>();

This QTime enclosed in the angled brackets lets the compiler know what QVariant will return. However, if the variable is not a QVariable the type enclosed in the angled brackets should not be used(doing so will result in a vague compile time error). So given that m_color is of type QColor you will rewrite

s.setValue("color/favorite", qVariantValue<QColor>(m_color));

to

s.setValue("color/favorite", m_color.value());

source

qVariantCanConvert is deprecated

replace

Q_ASSERT(qVariantCanConvert<QString>(variant));
Q_ASSERT(qVariantCanConvert<QSize>(variant));
Q_ASSERT(qVariantCanConvert<QFont>(fontVariant));

with

Q_ASSERT(variant.canConvert(QMetaType::QString));
Q_ASSERT(variant.canConvert(QMetaType::QSize));
Q_ASSERT(fontVariant.canConvert(QMetaType::QFont));

Qt::escape is deprecated

error: 'escape' is not a member of 'Qt'

So you would change the following block:

if (result == QString())
    result = Qt::escape(val.toString());
else
    result = Qt::escape(result);
return result;

to

if (result == QString())
    result = QString(val.toString()).toHtmlEscaped();
else
    result = QString(result).toHtmlEscaped();
return result;

this procedure can be automated by a porting tool from KDAB.

QDesktopServices::storageLocation deprecated

error: 'storageLocation' is not a member of 'QDesktopServices'
error: 'DataLocation' is not a member of 'QDesktopServices'

Use QStandardPaths::StandardLocation:

QString path = s.value("db.path", QDesktopServices::storageLocation(QDesktopServices::DataLocation)).toString();

to

QString path = s.value("db.path", QStandardPaths::standardLocations(QStandardPaths::DataLocation)).toString();

source

CONFIG+=qtestlib is deprecated

If you have the above line in your project file the compiler will warn you in the compile window, nonetheless the code will still run as usual:

Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.

QWeakPointer quirks

A code block like

quint64 decodedPointer = line.toULongLong();
MetaData* md = reinterpret_cast<MetaData*>(decodedPointer);
QWeakPointer<MetaData> wp(md);

results in

error: no matching function for call to 'QWeakPointer<MetaData>::QWeakPointer(MetaData*&)'

To fix this add to the project file:

DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0

source

QtConcurrent Library is Missing?

C:\Qt\5.0.2\5.0.2\mingw47_32\include\QtConcurrent\qtconcurrentthreadengine.h:133: error: undefined reference to 
`_imp___ZN12QtConcurrent16ThreadEngineBaseD2Ev'

In Qt 4, QtConcurrent was part of QtCore, so there was no need to include specific headers. This is no longer the case with Qt 5. If your source code has lines like

m_current = QtConcurrent::blockingMappedReduced(slices, functor, stitchReduce, QtConcurrent::UnorderedReduce );

You will need to include the header:

#include <QtConcurrent/QtConcurrent>

and add the following line to your project file:

QT+= concurrent

Fixing #include<> Headers

A Perl script "fixqt4headers.pl" exists in qtbase/bin/. that should be run on source code using Qt that corrects the #include<> directives for Qt components to also consider the module name.

Plugin loading

The Q_EXPORT_PLUGIN,Q_EXPORT_PLUGIN2 macros have been deprecated in favor of the new Q_PLUGIN_METADATA macro. The advantage of the new system is that it allows Qt to query the metadata for the plugin without actually dlopen'ing it. This greatly improves performance and reliability of the plugin system.

The new Q_PLUGIN_METADATA macro is included next to the Q_OBJECT macro in the QObject derived class that is returned when loading the plugin. It contains the plugins IID and a filename pointing to a json file containing the metadata for the plugin. The json file is compiled into the plugin and does not need to be installed.

An example on how to change your plugins can be found by looking at the patch that changes the Gif image format plugin, see http://code.qt.io/cgit/qt/qtbase.git/commit/?id=963b4c1647299fd023ddbe7c4a25ac404e303c5d

Deploying to systems without C++11

When Qt is built from source code on a system with C++11 installed, the Qt libraries/frameworks are linked against the system's C++11 library (libc). This means that the Qt libraries/frameworks are not deployable to systems without C++11 installed (such as out-of-the-box Mac OS X 10.6). To be able to deploy to systems that only support the older C++ standard (libstdc++), build Qt from source code with the -no-c++11 configure option.

QTimer is no longer accurate to the millisecond by default

QTimer has now 3 accuracy types, with a new default behaviour:

  • The new default type is Qt::CoarseTimer which, to reduce power/CPU consumption, allow 5% difference between requested time and actual one, and even allow the timer to fire before the requested time.
  • The former one is Qt::PreciseTimer (to the millisecond, never before the requested time).
  • A third one is Qt::VeryCoarseTimer and allow a 1 second difference

QUrl addQueryItem moved to QUrlQuery

If you have:

QUrl url;
// …
url.addQueryItem(key, value);

You will want to change it to

QUrl url;
QUrlQuery urlQuery(url);        //initialize with url to append to existing query, if present
// …
urlQuery.addQueryItem(key, value);

url.setUrlQuery(urlQuery);

The same applies to the QUrl::getQueryItem() methods. They have been moved to QUrlQuery.

QAbstractItemModel changes

void reset()
void setRoleNames(const QHash<int, QByteArray> & roleNames)

both have changed and are now obsolete.

See Obsolete Members for QAbstractItemModel

QHeaderView changes

Use
void QHeaderView::setSectionResizeMode(QHeaderView::ResizeMode mode)
instead of
void QHeaderView::setResizeMode(ResizeMode mode)
The latter has been removed.

Recommended Reading