Vous êtes sur la page 1sur 9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

TransitionfromQt4.xtoQt5
FromQtWiki
EnArBgDeElEsFaFiFrHiHuItJaKnKoMsNlPlPtRuThTrUkZh
ThetransitionfromQt4.xtoQt5isnotexpectedtobesignificant.However,the"modularization"oftheQt
codebaserequiressomeamountofchangestoprojectconfiguration,suchasuseof"headers",and
configurationofprojectbuildsettings(suchaschangestothe*.profiles).
QtCreator(master)iscompiledusingQt4andQt5youcanrefertoitssourcestogetanoverviewofwhat
isrequiredtoportanapplicationandkeepthesourcesbackwardscompatibletoQt4.

QtWidgetsasa
SeparateModule

Contents

examplecompiletimeerrors
error:QMainWindow:Nosuchfileordirectory
error:QToolButton:Nosuchfileordirectory
error:QWidget:Nosuchfileordirectory

Solution
Addthisinyour*.profile:
QT+=widgets

Changeallinstancesof
#include<QtGui>

to
#include<QtWidgets>

Thecodeshouldworknow,though
sometimesyoumayrequiretobe
moreexplicit:

1QtWidgetsasaSeparateModule
1.1examplecompiletimeerrors
1.2Solution
2QtWebKitWidgetsisalsoaseparatemodule:
2.1examplecompiletimeerrors
2.2Solution
3QPrinterDoesn'tWork
4toAscii()andfromAscii()Methodsaredeprecated
5QCoreApplication::UnicodeUTF8isdeprecated
6QWorkspaceisdeprecated
7QDragProblems
8qFindChildrenisdeprecated
9qVariantValueisdeprecated
10qVariantCanConvertisdeprecated
11Qt::escapeisdeprecated
12QDesktopServices::storageLocationdeprecated
13CONFIG+=qtestlibisdeprecated
14QWeakPointerquirks
15QtConcurrentLibraryisMissing?
16Fixing#include<>Headers
17Pluginloading
18DeployingtosystemswithoutC++11
19QTimerisnolongeraccuratetothemillisecondbydefault
20QUrladdQueryItemmovedtoQUrlQuery
21QAbstractItemModelchanges
22RecommendedReading

#include<QtWidgets/QToolButton>
http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

1/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

QtWebKitWidgetsisalsoaseparatemodule:
examplecompiletimeerrors
error:invaliduseofincompletetype'classQWebFrame'
error:forwarddeclarationof'classQWebFrame'

Solution
Addthisinyour*.profile:
QT+=webkitwidgets

Note:whenyouhaveQT+=webkitwidgetsyoudon'tneedQT+=widgets
Inaddition,replaceallinstancesof
#include<QtWebKit>

to
#include<QtWebKitWidgets>

YoucantrythisbyportingaWYSISWYGhtmleditor(http://qt.gitorious.org/qtlabs/graphics
dojo/trees/c8d0c381b994d7417863832929cc4c3f710f2db5/htmleditor)fromQt4toQt5.

QPrinterDoesn'tWork
Ifyourcodehasthefollowinglines:
#include<QPrinter>
#include<QPrintDialog>

addthefollowingtoyourprojectfile:
QT+=printsupport

Again,sometimesitmaynotworkandyouwouldneedtobeexplicit:
#include<QtPrintSupport/QPrinter>
#include<QtPrintSupport/QPrintDialog>

http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

2/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

toAscii()andfromAscii()Methodsaredeprecated
Replaceallinstancesof
fromAscii()
toAscii()

to
fromLatin1()
toLatin1()

Forexample,giventheQt4code
QByteArrayconfigfileti=TMP_Config.toAscii();

youwouldchangeto
QByteArrayconfigfileti=TMP_Config.toLatin1();

QCoreApplication::UnicodeUTF8isdeprecated
Thisenumtypeusedtodefinethe8bitencodingofcharacterstringargumentstotranslate().Thisenumis
nowobsoleteandUTF8willbeusedinallcases.Soremoveallinstancesof
QCoreApplication::UnicodeUTF8.Forexample:
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));

QWorkspaceisdeprecated
ThisclassisobsoleteandwasreplacedbytheQMdiAreaclassinQt4.3.InQt5QWorkspacehasbeen
removed.ThenewclasshasasimilarAPItoQWorkspaceandportingitonlyinvolvedchangingthenames
ofafewmethods,signals,andslots.
replace
http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

3/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

#include<QWorkspace>

with
#include<QMdiArea>

QDragProblems
Appsthathasdropanddragfunctionalitywillneedsometweaking.Alinesuchas
QDrag*drag=newQDrag(event>widget());

inQt5willgeneratetheerror
error:nomatchingfunctionforcallto'QDrag::QDrag(QWidget*)'

Tofixthisaddamongtheincludes:
#include<QWidget>

qFindChildrenisdeprecated
Anerrorwillpopofthisfashion:
error:'qFindChildren'wasnotdeclaredinthisscope

TosolvethisyoureplaceqFindChildrenwithfindChildren,forexamplein
toString(constQObject*obj,intindentLevel)const{
[]
/*QueryoverQObjects*/
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());

http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

4/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

source(https://bugs.webkit.org/attachment.cgi?id=82025&action=diff)

qVariantValueisdeprecated
Yourcompilerwillsay
error:'qVariantValue'wasnotdeclaredinthisscope

ThisfunctionisequivalenttoQVariant::value<T>(value).ThereforeifgivenaQVariantvalrewritetheline
QTimet=qVariantValue<QTime>(val);

to
QTimet=val.value<QTime>();

ThisQTimeenclosedintheangledbracketsletsthecompilerknowwhatQVariantwillreturn.However,if
thevariableisnotaQVariablethetypeenclosedintheangledbracketsshouldnotbeused(doingsowill
resultinavaguecompiletimeerror).Sogiventhatm_colorisoftypeQColoryouwillrewrite
s.setValue("color/favorite",qVariantValue<QColor>(m_color));

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

source(http://stackoverflow.com/questions/14919867/qvariantvalueisqtdeprecatedwhatisthe
replacement)

qVariantCanConvertisdeprecated
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));

http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

5/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

Qt::escapeisdeprecated
error:'escape'isnotamemberof'Qt'

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

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

thisprocedurecanbeautomatedbyaportingtool(http://www.kdab.com/automatedportingfromqt4to
qt5/)fromKDAB.

QDesktopServices::storageLocationdeprecated
error:'storageLocation'isnotamemberof'QDesktopServices'
error:'DataLocation'isnotamemberof'QDesktopServices'

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

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

source(http://doc.qt.io/qt5/QDesktopServices.html)

CONFIG+=qtestlibisdeprecated
Ifyouhavetheabovelineinyourprojectfilethecompilerwillwarnyouinthecompilewindow,
nonethelessthecodewillstillrunasusual:
ProjectWARNING:CONFIG+=qtestlibisdeprecated.UseQT+=testlibinstead.

http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

6/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

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

resultsin
error:nomatchingfunctionforcallto'QWeakPointer<MetaData>::QWeakPointer(MetaData*&)'

Tofixthisaddtotheprojectfile:
DEFINES+=QT_DISABLE_DEPRECATED_BEFORE=0

source(http://forum.qt.io/viewthread/27510)

QtConcurrentLibraryisMissing?
C:\Qt\5.0.2\5.0.2\mingw47_32\include\QtConcurrent\qtconcurrentthreadengine.h:133:error:undefinedreferenceto
`_imp___ZN12QtConcurrent16ThreadEngineBaseD2Ev'

InQt4,QtConcurrentwaspartofQtCore,sotherewasnoneedtoincludespecificheaders.Thisisno
longerthecasewithQt5.Ifyoursourcecodehavelineslike
m_current=QtConcurrent::blockingMappedReduced(slices,functor,stitchReduce,QtConcurrent::UnorderedReduce);

Youwillneedtoincludetheheader:
#include<QtConcurrent/QtConcurrent>

andaddthefollowinglinetoyourprojectfile:
QT+=concurrent

Fixing#include<>Headers
APerlscript"fixqt4headers.pl"existsinqtbase/bin/.thatshouldberunonsourcecodeusingQtthat
correctsthe#include<>directivesforQtcomponentstoalsoconsiderthemodulename.

Pluginloading
http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

7/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

TheQ_EXPORT_PLUGIN,Q_EXPORT_PLUGIN2macroshavebeendeprecatedinfavorofthenew
Q_PLUGIN_METADATAmacro.TheadvantageofthenewsystemisthatitallowsQttoquerythe
metadataforthepluginwithoutactuallydlopen'ingit.Thisgreatlyimprovesperformanceandreliabilityof
thepluginsystem.
ThenewQ_PLUGIN_METADATAmacroisincludednexttotheQ_OBJECTmacrointheQObject
derivedclassthatisreturnedwhenloadingtheplugin.ItcontainsthepluginsIIDandafilenamepointingto
ajsonfilecontainingthemetadatafortheplugin.Thejsonfileiscompiledintothepluginanddoesnot
needtobeinstalled.
AnexampleonhowtochangeyourpluginscanbefoundbylookingatthepatchthatchangestheGifimage
formatplugin,seehttp://code.qt.io/cgit/qt/qtbase.git/commit/?
id=963b4c1647299fd023ddbe7c4a25ac404e303c5d

DeployingtosystemswithoutC++11
WhenQtisbuiltfromsourcecodeonasystemwithC++11installed,theQtlibraries/frameworksarelinked
againstthesystem'sC++11library(libc).ThismeansthattheQtlibraries/frameworksarenotdeployableto
systemswithoutC++11installed(suchasoutoftheboxMacOSX10.6).Tobeabletodeploytosystems
thatonlysupporttheolderC++standard(libstdc++),buildQtfromsourcecodewiththenoc++11
configureoption.

QTimerisnolongeraccuratetothemillisecondbydefault
QTimerhasnow3accuracytypes,withanewdefaultbehaviour:
ThenewdefaulttypeisQt::CoarseTimerwhich,toreducepower/CPUconsumption,allow5%
differencebetweenrequestedtimeandactualone,andevenallowthetimertofirebeforethe
requestedtime.
TheformeroneisQt::PreciseTimer(tothemillisecond,neverbeforetherequestedtime).
AthirdoneisQt::VeryCoarseTimerandallowa1seconddifference

QUrladdQueryItemmovedtoQUrlQuery
Ifyouhave:
QUrlurl;
//
url.addQueryItem(key,value);

Youwillwanttochangeitto
QUrlurl;
QUrlQueryurlQuery;
//
urlQuery.addQueryItem(key,value);

url.setUrlQuery(urlQuery);

http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

8/9

10/10/2015

TransitionfromQt4.xtoQt5QtWiki

QAbstractItemModelchanges
voidreset()
voidsetRoleNames(constQHash<int,QByteArray>&roleNames)

bothhavechangedandarenowobsolete.
SeeObsoleteMembersforQAbstractItemModel(http://doc.qt.io/qt5/qabstractitemmodelobsolete.html)

RecommendedReading
C++APIChanges(http://doc.qt.io/qt5/sourcebreaks.html)
Theportingguide(http://doc.qt.io/qt5/portingguide.html)
PortingDesktopApplicationsfromQt4toQt5(http://www.ics.com/blog/portingdesktop
applicationsqt4qt5)
PortingfromQt4toQt5(http://www.kdab.com/portingfromqt4toqt5/)
AutomatedportingfromQt4toQt5(http://www.kdab.com/automatedportingfromqt4toqt5/)
Retrievedfrom"http://wiki.qt.io/index.php?title=Transition_from_Qt_4.x_to_Qt5&oldid=19502"
Categories: DevelopingwithQt DevelopingQt
Thispagewaslastmodifiedon5September2015,at20:29.
Thispagehasbeenaccessed29,717times.

http://wiki.qt.io/Transition_from_Qt_4.x_to_Qt5

9/9

Vous aimerez peut-être aussi