You're probably looking at this page because you want to port your application from Qt 1.x to Qt 2.x, but to be sure, let's review the good reasons to do this:
The Qt 2.x series is not binary compatible with the 1.x series. This means programs compiled for Qt 1.x must be recompiled to work with Qt 2.x. Qt 2.x is also not completely source compatible with 1.x, however all points of incompatibility cause compiler errors (rather than mysterious results), or produce run-time messages. The result is that Qt 2.x includes many additional features, discards obsolete functionality that is easily converted to use the new features, and that porting an application from Qt 1.x to Qt 2.x is a simple task well worth the amount of effort required.
To port code using Qt 1.x to use Qt 2.x:
Many very major projects, such as KDE have been port, so there is plenty of expertise in the collective conscious that is the Qt Developer Community!
Qt 2.x is namespace-clean, unlike 1.x. Qt now uses very few
global identifiers. Identifiers like red, blue, LeftButton,
AlignRight, Key_Up, Key_Down, NoBrush
etc. are now part of a
special class Qt
(defined in qnamespace.h),
which is inherited by
most Qt classes. Member functions of classes that inherit from QWidget,
etc. are totally unaffected, but code that is
not in functions of classes inherited from Qt
,
you must qualify these identifiers like this: Qt::red,
Qt::LeftButton, Qt::AlignRight
, etc.
The qt/bin/qt20fix
script helps to fix the code that
needs adaption, though most code does not need changing.
Compiling with -DQT1COMPATIBILITY will help you get going with Qt 2.x - it allows all the old "dirty namespace" identifiers from Qt 1.x to continue working. Without it, you'll get compile errors that can easily be fixed by searching this page for the clean identifiers.
In Qt 1.x, all widget constructors were defined with a default value of 0 for the parent widget. However, only the main window of the application should be created with a 0 parent, all other widgets should have parents. Having the 0 default made it too simple to create bugs by forgetting to specify the parent of non-mainwindow widgets. Such widgets would typically never be deleted (causing memory leaks), and they would become top-level widgets, confusing the window managers. Therefore, in Qt 2.x the 0 default parent has been removed for the widget classes that are not likely to be used as main windows.
Note also that programs no longer need (or should) use 0 parent just to indicate that a widget should be top-level. See
QWidget::isTopLevel()for details. See also the notes about QPopupMenu and QDialog below.
Some virtual functions have changed signature in Qt 2.x. If you override them in derived classes, you must change the signature of your functions accordingly.
QWidget::setStyle(GUIStyle)
QListView::addColumn(const char *, int)
QListView::setColumnText(int, const char *)
QListViewItem::setText(int, const char *)
QMultiLineEdit::insertLine(const char *, int)
QMultiLineEdit::insertAt(const char *, int, int, bool)
QSpinBox::setPrefix(const char *)
QSpinBox::setSuffix(const char *)
QToolButton::setTextLabel(const char *, bool)
QDoubleValidator::validate(QString &, int &)
QIntValidator::validate(QString &, int &)
QValidator::fixup(QString &)
QSlider::paintSlider(QPainter *, const QRect &)
This is one class of changes that are not detected by the compiler, so you should mechanically search for each of these function names in your header files, eg.
egrep -w 'setStyle|addColumn|setColumnText|setText...' *.h
Of course, you'll get a few false positives (eg. if you have a setText function that is not in a subclass of QListViewItem).
The collection classes include generic classes such as QGDict, QGList, and the subclasses such as QDict and QList.
The macro-based Qt collection classes are obsolete; use the
template-based classes instead. Simply remove includes of qgeneric.h and
replace e.g. Q_DECLARE(QCache,QPixmap) with QCache The GCI global typedef is replaced by QCollection::Item. Only if you
make your own subclasses of the undocumented generic collection classes
will you have GCI in your code.
This change has been made to avoid collisions with other namespaces.
The GCF global typedef is removed (it was not used in Qt).
The ASSERT macro is now a null expression if the CHECK_STATE flag
is not set (i.e. if the NO_CHECK flag is defined).
The debug() function now outputs nothing if Qt was compiled with
the NO_DEBUG macro defined.
QString has undergone major changes internally, and although it is highly
backward compatible, it is worth studying in detail when porting to Qt 2.x.
The Qt 1.x QString class has been renamed to QCString in Qt 2.x, though if
you use that you will incur a performance penalty since all Qt functions
that took const char* now take const QString&.
To take full advantage of the new Internationalization
functionality in Qt 2.x, the following steps are required:
If you find that you are mixing usage of QCString, QString,
and QByteArray, this causes lots of unnecessary copying and
might indicate that the true nature of the data you are
dealing with is uncertain. If the data is NUL-terminated
8-bit data, use QCString; if it is unterminated (ie.
contains NULs) 8-bit data, use QByteArray; if it is text,
use QString.
to catch places where
Unicode information is being converted to ASCII (loosing
information if your user in not using Latin1). Qt has
a small number of calls to this - ignore those. As a stricter
alternative, compile your code with QT_NO_ASCII_CAST defined,
which hides the automatic conversion of QString to const char*,
so you can catch problems at compile time.
Points to note about the new QString are:
In Qt 1.x the constructor was used in two ways: accidentally,
by attempting to convert a char to a QString (the char converts to int!) -
giving strange bugs, and as a way to make a QString big enough prior to
calling
Also see QStrList.
to the old
signals and slots, usually with a message indicating the const QString&
replacement signal/slot.
Especially look out for this type of code:
This creates a string 2 characters long.
To find these problems while converting, you might like to
add ASSERT(strlen(d->ascii)==d->len) inside
The Standard C++ Library string is not Unicode. Nor is wstring defined
to be so (for the small number of platforms where it is defined at all).
This is the same mistake made over and over
in the history of C - only when non-8-bit characters are the norm
do programmers find them usable. Though it is possible to convert between
string and QString, it is less efficient than using QString throughout.
For example, when using:
if you use string, like this:
that will create a (ASCII only) copy of str, stored in mylabel.
But this:
will make an implicitly shared reference to str in the QLabel - no copying
at all. This function might be 10 nested function calls away from something
like this:
At this point, in Qt 2.x, the tr() does a very fast dictionary lookup
through memory-mapped message files, returning some Unicode QString for
the appropriate language (the default being to just make a QString out
of the text, of course - you're not forced to use any of these
features), and that same memory mapped Unicode will be passed
though the system. All occurrences of the translation of "Okay" can
potentially be shared.
In the function
All colors
(color0,
color1,
black,
white,
darkGray,
gray,
lightGray,
red,
green,
blue,
cyan,
magenta,
yellow,
darkRed,
darkGreen,
darkBlue,
darkCyan,
darkMagenta,
and
darkYellow)
are in the Qt namespace.
In members of classes that inherit the Qt namespace-class (eg. QWidget
subclasses), you can use the unqualified names as before, but in global
functions (eg. main()), you need to qualify them: Qt::red, Qt::white, etc.
See also the QRgb section below.
In QRgb (a typedef of long), the order of the RGB channels has changed to
be in the more efficient order (for typical contemporary hardware). If your
code made assumptions about the order, you will get blue where you expect
red and vice versa (you'll not notice the problem if you use shades of
grey, green, or magenta). You should port your code to use the
creator function qRgb(int r,int g,int b) and the
access functions qRed(QRgb), qBlue(QRgb), and qGreen(QRgb).
If you are using the alpha channel, it hasn't moved, but you should use
the functions qRgba(int,int,int,int) and qAlpha(QRgb). Note also that
QColor::pixel() does not return a QRgb (it never did on all platforms,
but your code may have assumed so on your platform) - this may also produce
strange color results - use QColor::rgb() if you want a QRgb.
The QDatastream serialization format of most Qt classes is changed
in Qt 2.x. Use If you want to write Qt 1.x format datastreams, note the following
compatibility issues:
This function is now called reparent().
This function is removed.
Calls like QWidget::setAcceptFocus(TRUE) should be replaced by
paintEvent(0) is not permitted - subclasses need not check for
a null event, and might crash.
Never pass 0 as the argument to paintEvent(). You probably
just want repaint() or update() instead.
When processing a paintEvent, painting is only permitted within
the update region specified in the event. Any painting outside will be
clipped away. This shouldn't break any code (it was always like this
on MS-Windows) but makes many explicit calls to
QPainter::setClipRegion() superfluous. Apart from the improved
consistency, the change is likely to reduce flicker and to make Qt
event slightly faster.
The protected member QIODevice::index is renamed to QIODevice::ioIndex
to avoid warnings and to allow compilation with bad C libraries that
check every occurrence of the string "index" in the implementation, since
a compiler will not always catch cases like
that need to be changed.
have been renamed to
Previously, setting a movie on a label cleared the value of text().
Now it doesn't. If you somehow used QLabel::text()
to detect if a
movie was set, you might have trouble. This is unlikely.
The semantics of the parent pointer changed for non-modal dialogs:
In Qt-2.x, dialogs are always toplevel windows. The parent, however,
takes the ownership of the dialog, i.e. it will delete the dialog at
destruction if it has not been explicitly deleted
already. Furthermore, the window system will be able to tell that both
the dialog and the parent belong together. Some X11 window managers
will for instance provide a common taskbar entry in that case.
If the dialog belongs to a toplevel main window
of your application, pass this main window as parent to the dialog's
constructor. Old code (with 0 pointer) will still run. Old code that
included QDialogs as child widgets will no longer work (it never really did).
If you think you might be doing this, put a breakpoint in
QDialog::QDialog() conditional on parent not being 0.
Many methods that took a QStrList can now instead take a QStringList,
which is a real list of QString values.
To use QStringList rather than QStrList, change loops that look like this:
to be like this:
In general, the QStrList functions are less efficient, building a temporary QStringList.
The following functions now use QStringList rather than QStrList
for return types/parameters.
The following functions are added:
The rarely used static function void
QFont::listSubstitutions(QStrList*) is replaced by QStringList
QFont::substitutions().
Calling resize(0,0) or resize(1,1) will no longer work magically.
Remove all such calls. The default size of toplevel widgets will be their
sizeHint().
The default implementation of QWidget::sizeHint() will no longer
return just an invalid size; if the widget has a layout, it will return
the layout's preferred size.
The special maximum MaximumHeight/Width is now QWIDGETSIZE_MAX,
not QCOORD_MAX.
QBoxLayout::addWidget()
now interprets the alignment parameter more aggressively. A
non-default alignment now indicates that the widget should not grow to
fill the available space, but should be sized according to sizeHint().
If a widget is too small, set the alignment to 0. (Zero indicates no
alignment, and is the default.)
The class QGManager is removed. Subclasses of QLayout need to be rewritten
to use the new, much simpler QLayout API.
For typical layouts, all use of
setMinimumSize()
and
setFixedSize()
can be removed.
activate() is no longer necessary.
You might like to look at the QGrid, QVBox, and QHBox widgets - they offer
a simple way to build nested widget structures.
In Qt 1.x mouse events to the viewport where redirected to the
event handlers for the listview; in Qt 2.x, this functionality is
in QScrollView where mouse (and other position-oriented) events are
redirected to viewportMousePressEvent() etc, which in turn translate
the event to the coordinate system of the contents and call
contentsMousePressEvent() etc, thus providing events in the most
convenient coordinate system. If you overrode QListView::MouseButtonPress(),
QListView::mouseDoubleClickEvent(), QListView::mouseMoveEvent(), or
QListView::mouseReleaseEvent() you must instead override
viewportMousePressEvent(),
viewportMouseDoubleClickEvent(), viewportMouseMoveEvent(), or
viewportMouseReleaseEvent() respectively. New code will usually override
contentsMousePressEvent() etc.
The signal QListView::selectionChanged(QListViewItem *) can now be
emitted with a null pointer as parameter. Programs that use the
argument without checking for 0, may crash.
The protected function
changed to
QDropSite is obsolete. If you simply passed this, just remove
the inheritance of QDropSite and call
setAcceptDrops(TRUE) in the class
constructor.
If you passed something other than this,
your code will not work. A common case is passing
the
viewport() of a QListView,
in which case,
override the
viewportDragMoveEvent(),
etc.
functions rather than QListView's dragMoveEvent() etc. For other
cases, you will need to use an event filter to act on the drag/drop events
of another widget (as is the usual way to intercept foreign events).
The parameters in the signal
contentsMoving(int,int)
are now positive rather than negative values, coinciding with
setContentsPos(). Search for
connections you make to this signal, and either change the slot they are
connected to such that it also expects positive rather than negative
values, or introduce an intermediate slot and signal that negates them.
If you used drag and drop with QScrollView, you may experience the problem
described for QDropSite.
The class QUrlDrag is renamed to QUriDrag, and the API has been
broadened to include additional conversion routines, including
conversions to Unicode filenames (see the class documentation
for details). Note that in Qt 1.x
the QUrlDrag class used the non-standard MIME type "url/url",
while QUriDrag uses the standardized "text/uri-list" type. Other
identifiers affected by the Url to Uri change are
QUrlDrag::setUrls() and QUrlDrag::urlToLocalFile().
The GrayText painter flag has been removed. Use
setPen( palette().disabled().foreground() )
instead.
The RasterOp enum
(CopyROP,
OrROP,
XorROP,
NotAndROP,
EraseROP,
NotCopyROP,
NotOrROP,
NotXorROP,
AndROP, NotEraseROP,
NotROP,
ClearROP,
SetROP,
NopROP,
AndNotROP,
OrNotROP,
NandROP,
NorROP, LastROP)
is now part of the Qt namespace class, so if you
use it outside a member function, you'll need to prefix with Qt::.
The binary storage format of QPicture is changed, but the Qt 2.x
QPicture class can both read and write Qt 1.x format QPictures. No
special handling is required for reading; QPicture will automatically
detect the version number. In order to write a Qt 1.x format QPicture,
set the formatVersion parameter to 1 in the QPicture constructor.
For writing Qt 1.x format QPictures, the compatibility issues of QDataStream applies.
It is safe to try to read a QPicture file generated with Qt 2.x
(without formatVersion set to 1) with a program compiled with Qt
1.x. The program will not crash, it will just issue the warning
"QPicture::play: Incompatible version 2.x" and refuse to load the
picture.
The basic coordinate datatype in these classes, QCOORD, is now 32
bit (int) instead of a 16 bit (short). The const values QCOORD_MIN and
QCOORD_MAX have changed accordingly.
QPointArray is now actually, not only seemingly, a QArray of QPoint
objects. The semi-internal workaround classes QPointData and QPointVal
are removed since they are no longer needed; QPoint is used directly
instead. The function
provides the point array converted to short (16bit) coordinates for
use with external functions that demand that format.
QImage uses QRgb for the colors - see the changes to that.
is replaced by
or
- see the documentation
to choose which is best for your application. NormalOptim is most like
the Qt 1.x "TRUE" optimization.
In Qt 1.x, new menu items were assigned either an application-wide
unique identifier or an identifier equal to the index of the item, depending on the
insertItem(...) function used.
In Qt 2.x this confusing
situation has been cleaned up: generated identifiers are always
unique across the entire application.
If your code depends on generated ids
being equal to the item's index, a quick fix is to use
in the handling function instead. You may alternatively pass
as identifier when you insert the items.
Furthermore, QPopupMenus can (and should!) be created with a parent
widget now, for example the main window that is used to display the
popup. This way, the popup will automatically be destroyed together
with its main window. Otherwise you'll have to take care of the
ownership manually.
QPopupMenus are also reusable in 2.x. They may occur in different
locations within one menu structure or be used as both a menubar
drop-down and as a context popup-menu. This should make it possible to
significantly simplify many applications.
Last but not least, QPopupMenu no longer inherits QTableView. Instead,
it directly inherits QFrame.
and
are now const
functions. If your subclass reimplements validate() as a
non-const function,
you will get a compile error (validate was pure virtual).
In QLineEdit, QComboBox, and QSpinBox,
setValidator(...) now takes a const pointer to a QValidator, and
validator() returns a const pointer. This change highlights the fact
that the widgets do not take the ownership of the validator (a validator is
a QObject on its own, with its own parent - you can easily set the same validator
object on many different widgets), so changing the state of
such an object or deleting it is very likely a bug.
File and directory names are now always Unicode strings (ie. QString). If you used QString
in the past for the simplicity it offers, you'll probably have little consequence. However,
if you pass filenames to system functions rather than using Qt functions (eg. if you use the
Unix unlink() function rather than QFile::remove(), your code will probably
only work for Latin1 locales (eg. Western Europe, the U.S.). To ensure your code will support
filenames in other locales, either use the Qt functions, or convert the filenames via
boundingRect(char) is replaced by
boundingRect(QChar), but since
char auto-converts to QChar, you're not likely to run into problems
with this.
This class (which was just QWidget under a different name) has been
removed. If you used it, do a global search-and-replace of the word
"QWindow" with "QWidget".
The global #define macros in qevent.h have been replaced by an
enum in QEvent. Use e.g. QEvent::Paint instead of Event_Paint. Same
for all of:
Event_None,
Event_Timer,
Event_MouseButtonPress,
Event_MouseButtonRelease,
Event_MouseButtonDblClick,
Event_MouseMove,
Event_KeyPress,
Event_KeyRelease,
Event_FocusIn,
Event_FocusOut,
Event_Enter,
Event_Leave,
Event_Paint,
Event_Move,
Event_Resize,
Event_Create,
Event_Destroy,
Event_Show,
Event_Hide,
Event_Close,
Event_Quit,
Event_Accel,
Event_Clipboard,
Event_SockAct,
Event_DragEnter,
Event_DragMove,
Event_DragLeave,
Event_Drop,
Event_DragResponse,
Event_ChildInserted,
Event_ChildRemoved,
Event_LayoutHint,
Event_ActivateControl,
Event_DeactivateControl,
and
Event_User.
The Q_*_EVENT macros in qevent.h have been deleted. Use an
explicit cast instead. The macros were:
Q_TIMER_EVENT,
Q_MOUSE_EVENT,
Q_KEY_EVENT,
Q_FOCUS_EVENT,
Q_PAINT_EVENT,
Q_MOVE_EVENT,
Q_RESIZE_EVENT,
Q_CLOSE_EVENT,
Q_SHOW_EVENT,
Q_HIDE_EVENT,
and
Q_CUSTOM_EVENT.
QChildEvents are now sent for all QObjects, not just QWidgets.
You may need to add extra checking if you use a QChildEvent without
much testing of its values.
All these functions have been removed in
Qt 2.x. Most are simply cases where "const char*" has changed to
"const QString&", or when an enumeration type has moved into the Qt::
namespace (which, technically, is a new name, but your code will
compile just the same anyway). This list is provided for completeness.
Debug vs. Release
QString
QString::latin1()
QString::sprintf()
. In Qt 2.x, the accidental bug case is
prevented (you will get a compilation error) and QString::sprintf has
been made safe - you no longer need to pre-allocate space (though for
other reasons, sprintf is still a poor choice - eg. it doesn't pass Unicode).
The only remaining common case is conversion of 0 (NULL) to QString, which
would usually give expected results in Qt 1.x. For Qt 2.x the correct
syntax is to use QString::null, though note that
the default constructor, QString(), creates a null string too.
Assignment of 0 to a QString is ambiguous - assign
QString::null; you'll mainly find these in code that has been converted
from const char* types to QString.
This also prevents a common error case from Qt 1.x - in
that version, mystr = 'X' would not produce the expected
results and was always a programming error; in Qt 2.x, it works - making
a single-character string.
QObject::connect()
QString s = "fred";
s[1] = '\0';
// s.length() == 4
// s == "f\0ed"
// s.latin1() == "f"
s[1] = 'r';
// s == "fred"
// s.latin1() == "fred"
QString s(2);
s[0] = '?';
s[1] = 0;
QString::latin1()
.
QLabel::setText( const QString& )
void myclass::dostuffwithtext( const string& str )
{
mylabel.setText( QString(str.c_str()) );
}
void myclass::dostuffwithtext( const QString& str )
{
mylabel.setText( str );
}
void toplevelclass::initializationstuff()
{
doStuff( tr("Okay") );
}
QApplication
QApplication::setColorSpec()
,
PrivateColor and TrueColor are obsolete. Use ManyColor instead.
QColor
QRgb
QDataStream
QDataStream::setVersion( 1 )
to get a
datastream object that can read and write Qt 1.x format data streams.
QString::latin1().
QWidget
QWidget::recreate()
QWidget::setAcceptFocus(bool)
QWidget::setFocusPolicy(StrongFocus)
, and
calls like QWidget::setAcceptFocus(FALSE) should be replaced by
QWidget::setFocusPolicy(NoFocus)
.
Additional policies are TabFocus and ClickFocus.
QWidget::paintEvent()
QIODevice
(uint)index
QLabel
QLabel::setMargin()
QLabel::setMargin()
and QLabel::margin()
QLabel::setIndent()
and
QLabel::indent()
, respectively. This was done to avoid
collision with QFrame::setMargin(), which is now virtual.
QLabel::setMovie()
QDialog
QStrList
QStrList list = ...;
const char* s;
for ( s = list.first(); s; s = list.next() ) {
process(s);
}
QStringList list = ...;
QStringList::ConstIterator i;
for ( i = list.begin(); i != list.end(); ++i ) {
process(*i);
}
QLayout
QListView
QMultiLineEdit
QMultiLineEdit::textWidth(QString*)
QMultiLineEdit::textWidth(const QString&)
.
This is unlikely to be a problem, and you'll get a compile error
if you called it.
QClipboard
QClipboard::pixmap()
now returns a QPixmap, not a QPixmap*.
The pixmap
will be null if no pixmap is on the
clipboard. QClipboard now offers powerful MIME-based types on the
clipboard, just like drag-and-drop (in fact, you can reuse most of your
drag-and-drop code with clipboard operations).
QDropSite
QScrollView
QTextStream
operator<<(QTextStream&, QChar&)
does not skip whitespace.
operator<<(QTextStream&, char&)
does,
as was the case with Qt 1.x. This is for backward compatibility.
QUriDrag
QPainter
QPicture
QPoint, QPointArray, QSize and QRect
QPointArray::shortPoints()
QImage
QPixmap
QPixmap::convertToImage()
with bitmaps now guarantees that color0 pixels
become color(0) in the resulting QImage. If you worked around the lack of
this, you may be able to simplify your code. If you made assumptions
about the previous undefined behavior, the symptom will be inverted
bitmaps (eg. "inside-out" masks).
QPixmap::optimize(TRUE)
QPixmap::setOptimization(QPixmap::NormalOptim)
QPixmap::setOptimization(QPixmap::BestOptim)
QMenuData / QPopupMenu
QMenuData::indexOf(int id)
QMenuData::count()
QValidator (QLineEdit, QComboBox, QSpinBox)
QValidator::validate(...)
QValidator::fixup( QString & )
QFile, QFileInfo, QDir
QFile::encodeFilename()
and QFile::decodeFilename()
- but do it
just as you call the system function - code that mixes encoded and unencoded filenames
is very error prone. See the comments in QString, such as regarding QT_NO_ASCII_CAST that
can help find potential problems.
QFontMetrics
QWindow
QEvent
All the removed functions
Copyright © 2000 Trolltech Trademarks