Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

Porting to Qt 4

This document describes porting applications from Qt 3 to Qt 4. If you haven't yet made the decision about porting, or are unsure about whether it is worth it, take a look at the key features offered by Qt 4. See also Getting Ready for Qt 4 for tips on how to write Qt 3 code that is easy to port to Qt 4.

The Qt 4 series is not binary compatible with the 3 series. This means programs compiled for Qt 3 must be recompiled to work with Qt 4. Qt 4 is also not completely source compatible with 3, however nearly all points of incompatibility cause compiler errors or run-time messages (rather than mysterious results). Qt 4 includes many additional features and discards obsolete functionality. Porting from Qt 3 to Qt 4 is straightforward, and once completed makes the considerable additional power and flexibility of Qt 4 available for use in your applications.

To port code from Qt 3 to Qt 4:

  1. Briefly read the porting notes below to get an idea of what to expect.
  2. Be sure that your code compiles and runs well on all your target platforms with Qt 3.
  3. Add the line QT += qt3support to your .pro file if you use qmake; otherwise, edit your makefile or project file to link against the Qt3Support library and add -DQT3_SUPPORT to your compiler flags. (You might also need to specify other libraries. See What's New in Qt 4 for details.)
  4. Run the qt3to4 porting tool. The tool will go through your source code and adapt it to Qt 4.
  5. Follow the instructions in the Porting .ui Files to Qt 4 page to port Qt Designer files.
  6. Recompile with Qt 4. For each error, search below for related identifiers (e.g., function names, class names). This document mentions all relevant identifiers to help you get the information you need at the cost of being a little verbose.

The qt3to4 porting tool replaces occurrences of Qt 3 classes that don't exist anymore in Qt 4 with the corresponding Qt 3 support class; for example, QListBox is turned into Q3ListBox.

At some point, you might want to stop linking against the Qt 3 support library (Qt3Support) and take advantage of Qt 4's new features. The instructions below explain how to do that for each compatibility class.

In addition to the Qt3Support classes (such as Q3Action, Q3ListBox, and Q3ValueList), Qt 4 provides compatibility functions when it's possible for an old API to cohabit with the new one. For example, QString provides a QString::simplifyWhiteSpace() compatibility function that's implemented inline and that simply calls QString::simplified(). The compatibility functions are not documented here; instead, they are documented for each class.

If you have the line QT += qt3support in your .pro file, qmake will automatically define the QT3_SUPPORT symbol, turning on compatibility function support. You can also define the symbol manually (e.g., if you don't want to link against the Qt3Support library), or you can define QT3_SUPPORT_WARNINGS instead, telling the compiler to emit a warning when a compatibility function is called. (This works only with GCC 3.2+ and MSVC 7.)

If you get stuck, ask on the qt4-preview-feedback mailing list. If you are a licensed customer, you can also contact Trolltech support.

Table of contents:

Type Names

The table below lists the classes that have been renamed in Qt 4. If you compile your applications with QT3_SUPPORT defined, the old names will be available.

Whenever you see an occurrence of the name on the left, you can safely replace it with the Qt 4 equivalent in your program. The qt3to4 tool performs the conversion automatically.

Qt 3 class nameQt 4 class name
QIconSetQIcon
QWMatrixQMatrix
QGuardedPtrQPointer

The table below lists the enums and typedefs that have been renamed in Qt 4. If you compile your applications with QT3_SUPPORT defined, the old names will be available.

Whenever you see an occurrence of the name on the left, you can safely replace it with the Qt 4 equivalent in your program. The qt3to4 tool handles performs the conversion automatically.

Qt 3 type nameQt 4 type name
QApplication::ColorModeQApplication::ColorSpec
QButton::ToggleStateQCheckBox::ToggleState
QCursorShapeQt::CursorShape
QFile::FilterSpecQFile::Filters
QFile::PermissionSpecQFile::Permission
QFile::SortSpecQFile::SortFlags
QFile::StatusQFile::Error
QFileInfo::PermissionSpecQFile::Permission
QGrid::DirectionQt::Orientation
QGridWidget::DirectionQt::Orientation
QIODevice::Offsetqlonglong
QImage::ScaleModeQt::AspectRatioMode
QSize::ScaleModeQt::AspectRatioMode
QSocket::ErrorQ3Socket::Error
QSocket::StateQ3Socket::State
QStyle::SCFlagsQStyle::SubControls
QStyle::SFlagsQStyle::State
QTSQTextStream
QUrlDragQUriDrag
QWidget::FocusPolicyQt::FocusPolicy
Q_LLONGqlonglong
Q_ULLONGqulonglong
Qt::DockQt::ToolBarDock
Qt::MacintoshVersionQSysInfo::MacVersion
Qt::TextFlagsQt::TextFlag
Qt::WindowsVersionQSysInfo::WinVersion

Enum Values

The table below lists the enum values that have been renamed in Qt 4. If you compile your applications with QT3_SUPPORT defined, the old names will be available.

Whenever you see an occurrence of the name on the left, you can safely replace it with the Qt 4 equivalent in your program. The qt3to4 tool handles performs the conversion automatically.

Qt 3 enum value nameQt 4 enum value name
IO_AppendQIODevice::Append
IO_ReadOnlyQIODevice::ReadOnly
IO_ReadWriteQIODevice::ReadWrite
IO_TranslateQIODevice::Translate
IO_TruncateQIODevice::Truncate
IO_WriteOnlyQIODevice::WriteOnly
IO_RawQIODevice::Unbuffered
QAccessible::MoveableQAccessible::Movable
QApplication::CustomColorsQApplication::CustomColor
QApplication::NormalColorsQApplication::NormalColor
QButton::NoChangeQCheckBox::NoChange
QButton::OffQCheckBox::Off
QButton::OnQCheckBox::On
QChar::SingleQChar::NoDecomposition
QChar::byteOrderMarkQChar::ByteOrderMark
QChar::byteOrderSwappedQChar::ByteOrderSwapped
QChar::nbspQChar::Nbsp
QChar::nullQChar::Null
QChar::replacementQChar::ReplacementCharacter
QComboBox::AfterCurrentQComboBox::InsertAfterCurrent
QComboBox::AtBottomQComboBox::InsertAtBottom
QComboBox::AtCurrentQComboBox::InsertAtCurrent
QComboBox::AtTopQComboBox::InsertAtTop
QComboBox::BeforeCurrentQComboBox::InsertBeforeCurrent
QComboBox::NoInsertionQComboBox::NoInsert
QDir::DefaultFilterQDir::NoFilter
QDir::DefaultSortQDir::NoSort
QEvent::AccelQEvent::Shortcut
QEvent::AccelOverrideQEvent::ShortcutOverride
QEvent::CaptionChangeQEvent::WindowTitleChange
QEvent::ChildInsertedQEvent::ChildAdded
QEvent::IMComposeQEvent::InputMethodCompose
QEvent::IMEndQEvent::InputMethodEnd
QEvent::IMStartQEvent::InputMethodStart
QEvent::IconChangeQEvent::WindowIconChange
QEvent::LayoutHintQEvent::LayoutRequest
QEvent::ReparentQEvent::ParentChange
QFileInfo::ExeGroupQFile::ExeGroup
QFileInfo::ExeOtherQFile::ExeOther
QFileInfo::ExeOwnerQFile::ExeOwner
QFileInfo::ExeUserQFile::ExeUser
QFileInfo::ReadGroupQFile::ReadGroup
QFileInfo::ReadOtherQFile::ReadOther
QFileInfo::ReadOwnerQFile::ReadOwner
QFileInfo::ReadUserQFile::ReadUser
QFileInfo::WriteGroupQFile::WriteGroup
QFileInfo::WriteOtherQFile::WriteOther
QFileInfo::WriteOwnerQFile::WriteOwner
QFileInfo::WriteUserQFile::WriteUser
QFrame::GroupBoxPanelQFrame::StyledPanel
QFrame::LineEditPanelQFrame::StyledPanel
QFrame::MenuBarPanelQFrame::StyledPanel
QFrame::PopupPanelQFrame::StyledPanel
QFrame::TabWidgetPanelQFrame::StyledPanel
QFrame::ToolBarPanelQFrame::StyledPanel
QImage::ScaleFreeQt::IgnoreAspectRatio
QImage::ScaleMaxQt::KeepAspectRatioByExpanding
QImage::ScaleMinQt::KeepAspectRatio
Qt::IdenticalQKeySequence::ExactMatch
Qt::NoMatchQKeySequence::NoMatch
Qt::PartialMatchQKeySequence::PartialMatch
QLayout::AutoQLayout::SetDefaultConstraint
QLayout::FixedQLayout::SetFixedSize
QLayout::FreeResizeQLayout::SetNoConstraint
QLayout::MinimumQLayout::SetMinimumSize
QMacStyle::SizeNoneQMacStyle::SizeDefault
QSettings::GlobalQSettings::SystemScope
QSettings::UserQSettings::UserScope
QSize::ScaleFreeQt::IgnoreAspectRatio
QSize::ScaleMaxQt::KeepAspectRatioByExpanding
QSize::ScaleMinQt::KeepAspectRatio
QSizePolicy::HorizontalQSizePolicy::Horizontally
QSizePolicy::VerticalQSizePolicy::Vertically
QSlider::AboveQSlider::TicksAbove
QSlider::BelowQSlider::TicksBelow
QSlider::BothQSlider::TicksBothSides
QSlider::LeftQSlider::TicksLeft
QSlider::NoMarksQSlider::NoTicks
QSlider::RightQSlider::TicksRight
QSocket::ClosingQ3Socket::Closing
QSocket::ConnectedQ3Socket::Connected
QSocket::ConnectingQ3Socket::Connecting
QSocket::ConnectionQ3Socket::Connection
QSocket::ErrConnectionRefusedQ3Socket::ErrConnectionRefused
QSocket::ErrHostNotFoundQ3Socket::ErrHostNotFound
QSocket::ErrSocketReadQ3Socket::ErrSocketRead
QSocket::HostLookupQAbstractSocket::HostLookupState
QSocket::IdleQAbstractSocket::UnconnectedState
QSqlError::ConnectionQSqlError::ConnectionError
QSqlError::NoneQSqlError::NoError
QSqlError::StatementQSqlError::StatementError
QSqlError::TransactionQSqlError::TransactionError
QSqlError::UnknownQSqlError::UnknownError
QStyle::CC_ListViewQStyle::CC_Q3ListView
QStyle::SH_UnderlineAcceleratorQStyle::SH_UnderlineShortcut
QStyle::Style_ActiveQStyle::State_Active
QStyle::Style_AutoRaiseQStyle::State_AutoRaise
QStyle::Style_BottomQStyle::State_Bottom
QStyle::Style_ChildrenQStyle::State_Children
QStyle::Style_DefaultQStyle::State_None
QStyle::Style_DownQStyle::State_DownArrow
QStyle::Style_EditingQStyle::State_Editing
QStyle::Style_EnabledQStyle::State_Enabled
QStyle::Style_FocusAtBorderQStyle::State_FocusAtBorder
QStyle::Style_HasFocusQStyle::State_HasFocus
QStyle::Style_HorizontalQStyle::State_Horizontal
QStyle::Style_ItemQStyle::State_Item
QStyle::Style_MouseOverQStyle::State_MouseOver
QStyle::Style_NoChangeQStyle::State_NoChange
QStyle::Style_NoneQStyle::State_None
QStyle::Style_OffQStyle::State_Off
QStyle::Style_OnQStyle::State_On
QStyle::Style_OpenQStyle::State_Open
QStyle::Style_RaisedQStyle::State_Raised
QStyle::Style_RectangleQStyle::State_Rectangle
QStyle::Style_SelectedQStyle::State_Selected
QStyle::Style_SiblingQStyle::State_Sibling
QStyle::Style_SunkenQStyle::State_Sunken
QStyle::Style_TopQStyle::State_Top
QStyle::Style_UpQStyle::State_Up
QTabBar::RoundedAboveQTabBar::RoundedNorth
QTabBar::RoundedBelowQTabBar:: RoundedSouth
QTabBar::TriangularAboveQTabBar:: TriangularNorth
QTabBar::TriangularBelowQTabBar:: TriangularSouth
QTextEdit::MovePgDownQTextEdit::MovePageDown
QTextEdit::MovePgUpQTextEdit::MovePageUp
QToolButton::RightQToolButton::BesideIcon
QToolButton::UnderQToolButton::BelowIcon
QValidator::ValidQValidator::Intermediate
QVariant::IconSetQCoreVariant::Icon
QWidget::ClickFocusQt::ClickFocus
QWidget::NoFocusQt::NoFocus
QWidget::StrongFocusQt::StrongFocus
QWidget::TabFocusQt::TabFocus
QWidget::WheelFocusQt::WheelFocus
Qt::AlignAutoQt::AlignLeft
Qt::AltButtonQt::AltModifier
Qt::AscendingQt::AscendingOrder
Qt::BottomQt::DockBottom
Qt::BottomLeftQt::BottomLeftCorner
Qt::BottomRightQt::BottomRightCorner
Qt::BreakAnywhereQt::TextWrapAnywhere
Qt::ControlButtonQt::ControlModifier
Qt::CustomPatternQt::TexturePattern
Qt::DescendingQt::DescendingOrder
Qt::DontClipQt::TextDontClip
Qt::DontPrintQt::TextDontPrint
Qt::ExpandTabsQt::TextExpandTabs
Qt::IncludeTrailingSpacesQt::TextIncludeTrailingSpaces
Qt::KeyButtonMaskQt::KeyboardModifierMask
Qt::Key_BackSpaceQt::Key_Backspace
Qt::Key_BackTabQt::Key_Backtab
Qt::Key_MediaPrevQt::Key_MediaPrevious
Qt::Key_NextQt::Key_PageDown
Qt::Key_PriorQt::Key_PageUp
Qt::Key_aacuteQt::Key_Aacute
Qt::Key_acircumflexQt::Key_Acircumflex
Qt::Key_adiaeresisQt::Key_Adiaeresis
Qt::Key_aeQt::Key_AE
Qt::Key_agraveQt::Key_Agrave
Qt::Key_aringQt::Key_Aring
Qt::Key_atildeQt::Key_Atilde
Qt::Key_ccedillaQt::Key_Ccedilla
Qt::Key_eacuteQt::Key_Eacute
Qt::Key_ecircumflexQt::Key_Ecircumflex
Qt::Key_ediaeresisQt::Key_Ediaeresis
Qt::Key_egraveQt::Key_Egrave
Qt::Key_ethQt::Key_ETH
Qt::Key_iacuteQt::Key_Iacute
Qt::Key_icircumflexQt::Key_Icircumflex
Qt::Key_idiaeresisQt::Key_Idiaeresis
Qt::Key_igraveQt::Key_Igrave
Qt::Key_ntildeQt::Key_Ntilde
Qt::Key_oacuteQt::Key_Oacute
Qt::Key_ocircumflexQt::Key_Ocircumflex
Qt::Key_odiaeresisQt::Key_Odiaeresis
Qt::Key_ograveQt::Key_Ograve
Qt::Key_oslashQt::Key_Ooblique
Qt::Key_otildeQt::Key_Otilde
Qt::Key_thornQt::Key_THORN
Qt::Key_uacuteQt::Key_Uacute
Qt::Key_ucircumflexQt::Key_Ucircumflex
Qt::Key_udiaeresisQt::Key_Udiaeresis
Qt::Key_ugraveQt::Key_Ugrave
Qt::Key_yacuteQt::Key_Yacute
Qt::KeypadQt::KeypadModifier
Qt::LeftQt::DockLeft
Qt::MV_10_DOT_0QSysInfo::MV_10_0
Qt::MV_10_DOT_1QSysInfo::MV_10_1
Qt::MV_10_DOT_2QSysInfo::MV_10_2
Qt::MV_10_DOT_3QSysInfo::MV_10_3
Qt::MV_10_DOT_4QSysInfo::MV_10_4
Qt::MV_9QSysInfo::MV_9
Qt::MV_CHEETAHQSysInfo::MV_10_0
Qt::MV_JAGUARQSysInfo::MV_10_2
Qt::MV_PANTHERQSysInfo::MV_10_3
Qt::MV_PUMAQSysInfo::MV_10_1
Qt::MV_TIGERQSysInfo::MV_10_4
Qt::MV_UnknownQSysInfo::MV_Unknown
Qt::MetaButtonQt::MetaModifier
Qt::MinimizedQt::DockMinimized
Qt::NoAccelQt::TextHideMnemonic
Qt::OverlineQt::TextOverline
Qt::RightQt::DockRight
Qt::ShiftButtonQt::ShiftModifier
Qt::ShowPrefixQt::TextShowMnemonic
Qt::SingleLineQt::TextSingleLine
Qt::StrikeOutQt::TextStrikeOut
Qt::TopQt::DockTop
Qt::TopLeftQt::TopLeftCorner
Qt::TopRightQt::TopRightCorner
Qt::TornOffQt::DockTornOff
Qt::UnderlineQt::TextUnderline
Qt::UnmanagedQt::DockUnmanaged
Qt::WNorthWestGravityQt::WStaticContents
Qt::WRepaintNoEraseQt::WNoAutoErase
Qt::WStyle_DialogQt::WType_Dialog
Qt::WStyle_NoBorderExQt::WStyle_NoBorder
Qt::WType_Modal(Qt::WType_Dialog | Qt::WShowModal)
Qt::WV_2000QSysInfo::WV_2000
Qt::WV_2003QSysInfo::WV_2003
Qt::WV_32sQSysInfo::WV_32s
Qt::WV_95QSysInfo::WV_95
Qt::WV_98QSysInfo::WV_98
Qt::WV_CEQSysInfo::WV_CE
Qt::WV_CENETQSysInfo::WV_CENET
Qt::WV_CE_basedQSysInfo::WV_CE_based
Qt::WV_DOS_basedQSysInfo::WV_DOS_based
Qt::WV_MeQSysInfo::WV_Me
Qt::WV_NTQSysInfo::WV_NT
Qt::WV_NT_basedQSysInfo::WV_NT_based
Qt::WV_XPQSysInfo::WV_XP
Qt::WordBreakQt::TextWordWrap
Qt::IbeamCursorQt::IBeamCursor

In addition, the following window flags have been either replaced with widget attributes or have been deprecated:

Qt 3 typeQt 4 equivalent
Qt::WDestructiveCloseUse QWidget::setAttribute(Qt::WA_DeleteOnClose) instead.
Qt::WStaticContentsUse QWidget::setAttribute(Qt::WA_StaticContents) instead.
Qt::WNorthWestGravity
Qt::WNoAutoEraseUse QWidget::setAttribute(Qt::WA_NoBackground) instead.
Qt::WResizeNoErase
Qt::WRepaintNoErase
Qt::WPaintCleverUnnecessary in Qt 4.
Qt::WMacNoSheetUnnecessary in Qt 4.

In Qt 4.1, the widget flags used to determine window modality have been replaced by a single enum that can be used to specify the modal behavior of top-level widgets:

Qt 3 typeQt 4 equivalent
Qt::WShowModalUse QWidget::setWindowModality(Qt::ApplicationModal) instead.
Qt::WGroupLeaderUse QWidget::setWindowModality(Qt::WindowModel) for each child dialog of the group leader, but do not change the modality of the group leader itself.

Properties

Some properties have been renamed in Qt 4, to make Qt's API more consistent and more intuitive. For example, QWidget's caption property has been renamed windowTitle to make it clear that it refers to the title shown in the window's title bar.

In addition, the property system has been extended to allow properties to be redefined in subclasses with the Q_PROPERTY() macro, removing the need for a Q_OVERRIDE macro.

The table below lists the Qt properties that have been renamed in Qt 4. Occurrences of these in Qt Designer .ui files are automatically converted to the new name by uic.

Qt 3 nameQt 4 name
QButton::accelQButton::shortcut
QButton::onQButton::checked
QButton::toggleButtonQAbstractButton::checkable
QDial::lineStepQDial::singleStep
QDial::maxValueQDial::maximum
QDial::minValueQDial::minimum
QDialog::modalQDialog::isModal
QLineEdit::editedQLineEdit::modified
QLineEdit::hasMarkedTextQLineEdit::hasSelectedText
QLineEdit::markedTextQLineEdit::selectedText
QObject::nameQObject::objectName
QProgressDialog::progressQProgressDialog::value
QProgressDialog::totalStepsQProgressDialog::maximum
QProgressDialog::wasCancelledQProgressDialog::wasCanceled
QPushButton::iconSetQPushButton::icon
QScrollBar::draggingSliderQScrollBar::sliderDown
QScrollBar::lineStepQScrollBar::singleStep
QScrollBar::maxValueQScrollBar::maximum
QScrollBar::minValueQScrollBar::minimum
QSlider::lineStepQSlider::singleStep
QSlider::maxValueQSlider::maximum
QSlider::minValueQSlider::minimum
QSpinBox::lineStepQSpinBox::singleStep
QSpinBox::maxValueQSpinBox::maximum
QSpinBox::minValueQSpinBox::minimum
QTabBar::currentTabQTabBar::currentIndex
QTabWidget::currentPageQTabWidget::currentWidget
QToolButton::iconSetQToolButton::icon
QToolButton::textLabelQToolButton::text
QWidget::captionQWidget::windowTitle
QWidget::iconQWidget::windowIcon
QWidget::iconTextQWidget::windowIconText

A handful of properties in Qt 3 are no longer properties in Qt 4, but the access functions still exist as part of the Qt 4 API. These are not used by Qt Designer; the only case where you need to worry about them is in highly dynamic applications that use Qt's meta-object system to access properties. Here's the list of these properties with the read and write functions that you can use instead:

Qt 3 propertyQt 4 read functionQt 4 write function
QSqlDatabase::connectOptionsQSqlDatabase::connectOptions()QSqlDatabase::setConnectOptions()
QSqlDatabase::databaseNameQSqlDatabase::databaseName()QSqlDatabase::setDatabaseName()
QSqlDatabase::hostNameQSqlDatabase::hostName()QSqlDatabase::setHostName()
QSqlDatabase::passwordQSqlDatabase::password()QSqlDatabase::setPassword()
QSqlDatabase::portQSqlDatabase::port()QSqlDatabase::setPort()
QSqlDatabase::userNameQSqlDatabase::userName()QSqlDatabase::setUserName()

Some properties have been removed from Qt 4, but the associated access functions are provided if QT3_SUPPORT is defined to help porting to Qt 4. When converting Qt 3 .ui files to Qt 4, uic generates calls to the Qt 3 compatibility functions.

The table below lists these properties with the read and write functions that you can use instead. The documentation for the individual functions explains how to replace them with non-compatibility Qt 4 functions.

Qt 3 propertyQt 4 read function (QT3_SUPPORT)Qt 4 write function (QT3_SUPPORT)
QMenuBar::separatorQMenuBar::separator()QMenuBar::setSeparator()
QPushButton::menuButtonQPushButton::isMenuButton()N/A
QTabWidget::marginQTabWidget::margin()QTabWidget::setMargin()
QTextEdit::textFormatQTextEdit::textFormat()QTextEdit::setTextFormat()
QWidget::backgroundBrushQWidget::backgroundBrush()N/A
QWidget::backgroundModeQWidget::backgroundMode()QWidget::setBackgroundMode()
QWidget::backgroundOriginQWidget::backgroundOrigin()QWidget::setBackgroundOrigin()
QWidget::colorGroupQWidget::colorGroup()QWidget::setColorGroup()
QWidget::customWhatsThisQWidget::customWhatsThis()QWidget::setCustomWhatsThis()
QWidget::inputMethodEnabledQWidget::inputMethodEnabled()QWidget::setInputMethodEnabled()
QWidget::ownCursorQWidget::ownCursor()N/A
QWidget::ownFontQWidget::ownFont()N/A
QWidget::ownPaletteQWidget::ownPalette()N/A
QWidget::paletteBackgroundColorQWidget::paletteBackgroundColor()QWidget::setPaletteBackgroundColor()
QWidget::paletteBackgroundPixmapQWidget::paletteBackgroundPixmap()QWidget::setPaletteBackgroundPixmap()
QWidget::paletteForegroundColorQWidget::paletteForegroundColor()QWidget::setPaletteForegroundColor()
QWidget::underMouseQWidget::underMouse()N/A

The following Qt 3 properties and their access functions are no longer available in Qt 4. In most cases, Qt 4 provides similar functionality.

Qt 3 propertyQt 4 equivalent
QButton::autoRepeatN/A
QButton::autoResizeCall QWidget:setFixedSize(QWidget::sizeHint()) whenever you change the contents.
QButton::exclusiveToggleSee QAbstractButton::autoExclusive.
QButton::pixmapUse QAbstractButton::icon instead.
QButton::toggleStateUse QCheckBox::setState() and QCheckBox::state() instead.
QButton::toggleTypeUse QCheckBox::setTristate() instead.
QComboBox::autoResizeCall QWidget:setFixedSize(QWidget::sizeHint()) whenever you change the contents.
QFrame::contentsRectUse Q3Frame::contentsRect() instead.
QFrame::marginUse QWidget::setContentsMargins() instead.
QTabBar::keyboardFocusTabN/A
QToolButton::offIconSetUse the off component of QAbstractButton::icon instead.
QToolButton::onIconSetUse the on component of QAbstractButton::icon instead.
QWidget::microFocusHintN/A

Explicit Sharing

Qt 4 is the first version of Qt that contains no explicitly shared classes. All classes that were explicitly shared in Qt 3 are implicitly shared in Qt 4:

This means that if you took a copy of an instance of the class (using operator=() or the class's copy constructor), any modification to the copy would affect the original and vice versa. Needless to say, this behavior is rarely desirable.

Fortunately, nearly all Qt 3 applications don't rely on explicit sharing. When porting, you typically only need to remove calls to detach() and/or copy(), which aren't necessary anymore.

If you deliberately rely on explicit sharing in your application, you can use pointers or references to achieve the same result in Qt 4.

For example, if you have code like

    void asciify(QByteArray array)
    {
        for (int i = 0; i < (int)array.size(); ++i) {
            if ((uchar)array[i] >= 128)
                array[i] = '?';
        }
    }

you can rewrite it as

    void asciify(QByteArray &array)
    {
        for (int i = 0; i < array.size(); ++i) {
            if ((uchar)array[i] >= 128)
                array[i] = '?';
        }
    }

(Notice the & in the parameter declaration.)

QAccel

The QAccel class has been renamed Q3Accel and moved to the Qt3Support module. In new applications, you have three options:

  1. You can use QAction and set a key sequence using QAction::setShortcut().
  2. You can use QShortcut, a class that provides similar functionality to Q3Accel.
  3. You can use QWidget::grabShortcut() and process "shortcut" events by reimplementing QWidget::event().

The Q3Accel class also supports multiple accelerators using the same object, by calling Q3Accel::insertItem() multiple times. In Qt 4, the solution is to create multiple QShortcut objects.

QAccessibleInterface

The QAccessibleInterface class has undergone some API changes in Qt 4, to make it more consistent with the rest of the Qt API.

If you have classes that inherit QAccessibleInterface or one of its subclasses (QAccessibleObject, QAccessibleWidget, etc.), you must port them the new QAccessibleInterface API.

See Virtual Functions for a list of QAccessibleInterface virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QAccessibleTitleBar

The QAccessibleTitleBar has been renamed Q3AccessibleTitleBar and moved to the Qt3Support library.

QAction

The QAction class has been redesigned in Qt 4 to integrate better with the rest of the menu system. It unifies the old QMenuItem class and the old QAction class into one class, avoiding unnecessary data duplication and the need to learn two different APIs.

The old QAction and QActionGroup classes have been renamed Q3Action and Q3ActionGroup and moved to Qt3Support. In addition, the new QAction class has compatibility functions to ease transition to Qt 4.

See Virtual Functions for a list of QAction virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QActionGroup

The QAction class has been completely redesigned in Qt 4 to integrate better with the rest of the menu system. See the section on QAction for details.

QApplication

The QApplication class has been split into two classes: QCoreApplication and QApplication. The new QApplication class inherits QCoreApplication and adds GUI-related functionality. In practice, this has no consequences for existing Qt applications.

In addition, the following API changes were made:

  1. QApplication::allWidgets() and QApplication::topLevelWidgets() used to return a pointer to a QWidgetList. Now they return a QWidgetList.

    Also, QWidgetList has changed from being a typedef for QPtrList<QWidget> to being a typedef for QList<QWidget *>. See the section on QWidgetList below for details.

    For example, if you have code like

            QWidgetList *list = QApplication::topLevelWidgets();
            QWidgetListIt it(*list);
            QWidget *widget;
            while ((widget = it.current())) {
                if (widget->inherits("MainWindow"))
                    ((MainWindow *)widget)->updateRecentFileItems();
                ++it;
            }
            delete list;

    you can rewrite it as

            QWidgetList list = QApplication::topLevelWidgets();
            for (int i = 0; i < list.size(); ++i) {
                if (MainWindow *mainWin = qobject_cast<MainWindow>(list.at(i)))
                    mainWin->updateRecentFileItems();
            }
  2. QApplication::setMainWidget() is no longer used. When all an application's windows are closed, the application will exit normally.

QAquaStyle

The QAquaStyle class first appeared in Qt 3.0, when the Qt/Mac port was first released. It emulated Apple's "Aqua" theme. In Qt 3.1, QAquaStyle was obsoleted by QMacStyle, which uses Appearance Manager to perform its drawing.

The QAquaStyle class is no longer provided in Qt 4. Use QMacStyle instead.

QAsciiCache<T>

QAsciiCache<T> has been renamed Q3AsciiCache<T> and moved to the Qt3Support library. It has been replaced by QCache<QByteArray, T>.

For details, read the section on QCache<T>, mentally substituting QByteArray for QString.

QAsciiDict<T>

QAsciiDict<T> and QAsciiDictIterator<T> have been renamed Q3AsciiDict<T> and Q3AsciiDictIterator<T> and moved to the Qt3Support library. They have been replaced by the more modern QHash<Key, T> and QMultiHash<Key, T> classes and their associated iterator classes.

When porting old code that uses Q3AsciiDict<T> to Qt 4, there are four classes that you can use:

For details, read the section on QDict<T>, mentally substituting QByteArray for QString.

QAsyncIO

The QAsyncIO class was used internally in Qt 2.x in conjunction with QImageConsumer. It was obsoleted in Qt 3.0. If you use this mechanism in your application, please submit a report to the Task Tracker on the Trolltech website and we will try to find a satisfactory substitute.

QBackInsertIterator

The undocumented QBackInsertIterator class has been removed from the Qt library. If you need it in your application, feel free to copy the source code from the Qt 3 <qtl.h> header file.

QBitArray

In Qt 3, QBitArray inherited from QByteArray. In Qt 4, QBitArray is a totally independent class. This makes very little difference to the user, except that the new QBitArray doesn't provide any of QByteArray's byte-based API anymore. These calls will result in a compile-time error, except calls to QBitArray::truncate(), whose parameter was a number of bytes in Qt 3 and a number of bits in Qt 4.

QBitArray was an explicitly shared class in Qt 3. See Explicit Sharing for more information.

The QBitVal class has been renamed QBitRef.

QButton

The QButton class has been replaced by QAbstractButton in Qt 4. Classes like QPushButton and QRadioButton inherit from QAbstractButton. As a help when porting older Qt applications, the Qt3Support library contains a Q3Button class implemented in terms of the new QAbstractButton.

If you used the QButton class as a base class for your own button type and want to port your code to the newer QAbstractButton, you need to be aware that QAbstractButton has no equivalent for the Q3Button::drawButton(QPainter *) virtual function. The solution is to reimplement QWidget::paintEvent() in your QAbstractButton subclass as follows:

    void MyButton::paintEvent(QPaintEvent *)
    {
        QPainter painter(this);
        drawButton(&painter);
    }

Q3Button functionQAbstractButton equivalent
Q3Button::autoResize()Call QWidget:setFixedSize(QWidget::sizeHint()) whenever you change the contents.
Q3Button::isExclusiveToggle()Use QAbstractButton::group() or QAbstractButton::autoExclusive() instead.
Q3Button::pixmap() constQAbstractButton::icon()
Q3Button::setAutoResize()N/A
Q3Button::setPixmap(const QPixmap &)QAbstractButton::setIcon(const QIcon &)
Q3Button::setState(ToggleState)See remark below
Q3Button::setToggleType(ToggleType)See remark below
Q3Button::state()See remark below
Q3Button::stateChanged(int)See remark below
Q3Button::toggleType()See remark below

Remarks:

  1. In Qt 3, QButton had a "toggle type", which could be QButton::SingleShot, QButton::Toggle, or QButton::Tristate. The new QAbstractButton class doesn't support "tristate" directly; this feature is implemented in QCheckBox instead. The two other "toggle types" (QButton::SingleShot and QButton::Toggle) are replaced by a QAbstractButton::checkable property.
  2. In Qt 3, QButton had a "toggle state", which could be QButton::Off, QButton::NoChange, or QButton::On. In Qt 4, this mechanism has been moved to QCheckBox.

See Virtual Functions for a list of QButton virtual member functions in Qt 3 that aren't virtual in Qt 4.

See Properties for a list of QButton properties in Qt 3 that have changed in Qt 4.

QButtonGroup

The QButtonGroup class has been completely redesigned in Qt 4. For compatibility, the old QButtonGroup class has been renamed Q3ButtonGroup and has been moved to Qt3Support. Likewise, the QHButtonGroup and QVButtonGroup convenience subclasses have been renamed Q3HButtonGroup and Q3VButtonGroup and moved to the Qt3Support library.

The old QButtonGroup, as well as Q3ButtonGroup, can be used in two ways:

  1. The button group is the parent widget of a number of buttons, i.e. the button group is the parent argument in the button constructor. The buttons are assigned identifiers 0, 1, 2, etc., in the order they are created. A Q3ButtonGroup can display a frame and a title because it inherits Q3GroupBox.
  2. The button group is an invisible widget and the contained buttons have some other parent widget. In this usage, each button must be manually inserted, using Q3ButtonGroup::insert(), into the button group and given an ID number.

Unlike Q3ButtonGroup, the new QButtonGroup doesn't inherit QWidget. It is very similar to a "hidden Q3ButtonGroup".

If you use a Q3ButtonGroup, Q3HButtonGroup, or Q3VButtonGroup as a widget and want to port to Qt 4, you can replace it with QGroupBox. In Qt 4, radio buttons with the same parent are automatically part of an exclusive group, so you normally don't need to do anything else. See also the section on QGroupBox below.

See Virtual Functions for a list of QButtonGroup virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QByteArray

In Qt 3, QByteArray was simply a typedef for QMemArray<char>. In Qt 4, QByteArray is a class in its own right, with a higher-level API in the style of QString.

Here are the main issues to be aware of when porting to Qt 4:

  1. The QMemArray(int size) constructor has been replaced with QByteArray(int size, char ch). The second argument specifies which character should be used for initializing the array; pass '\0' if you have no specific needs.

    For example, if you have code like

        QByteArray ba(64);

    you can rewrite it as

        QByteArray ba(64, '\0');
  2. QMemArray::at() returned a non-const reference, whereas the new QByteArray::at() returns a const value. Code like
        ba.at(0) = 'X';

    will no longer compile. Instead, use QByteArray::operator[]:

        ba[0] = 'X';
  3. The QMemArray::contains(char) function has been renamed QByteArray::count(char). In addition, there now exists a QByteArray::contains(char) function that returns a boolean value. Replace old calls to contains() with either count() or contains(), depending on whether you care about the specific number of occurrences of a character in the byte array or only care about whether the array contains that character or not.
  4. The new QByteArray has no assign() function. Calls to QMemArray::assign(const QMemArray &) can be replaced by calls to QByteArray::operator=(). Calls to QMemArray::assign(const T *, uint) have no equivalent in Qt 4; if you use it, the solution is either to use QByteArray::fromRawData() and to call free() yourself to avoid a memory leak, or to use the QByteArray(const char *, int) constructor, which will take a deep copy of the data.
  5. QMemArray::bsearch() and QMemArray::sort() have no equivalent in the new QByteArray class. Use qBinaryFind() and qSort() if you need that functionality.

QByteArray was an explicitly shared class in Qt 3. See Explicit Sharing for more information.

QCache<T>

QCache<T> has been renamed Q3Cache<T> and moved to Qt3Support. The new QCache class has a different API, and takes different template parameters: QCache<Key, T>.

When porting to Qt 4, QCache<QString, T> is the obvious substitute for Q3Cache<T>. The following table summarizes the API differences.

Q3Cache<T> functionQCache<QString, T> equivalent
Q3Cache::Q3Cache(int maxCost, int size, bool caseSensitive)See remark below
Q3Cache::autoDelete()N/A
Q3Cache::count()QCache::count() or QCache::size() (equivalent)
Q3Cache::setAutoDelete()See remark below
Q3Cache::size()N/A
Q3Cache::statistics()N/A
Q3Cache::operator=()See remark below

Remarks:

  1. Q3Cache requires the user to allocate a specific number of buckets by passing a prime number (17 by default) to the constructor. In contrast, the new QCache's hash table automatically grows and shrinks as needed, and the constructor doesn't take a prime number.
  2. Q3Cache supportes case-insensitive lookups by passing false as second argument to the constructor. This feature has no equivalent in QMultiHash. Instead, call QString::toLower() before you insert or lookup a key in the hash.
  3. The Q3Cache::insert() function returns a bool value that indicates whether or not the item actually was inserted in the cache. If the item wasn't inserted, it was the caller's responsibility to delete the item. The new QCache::insert() function returns void and either adds it to the cache or deletes it right away. Old code like
        if (!cache.insert(key, object))
            delete object;

    becomes

        cache.insert(key, object);
  4. The new QCache class always takes ownership of the items it stores (i.e. auto-delete is always on). If you use Q3Cache with auto-delete turned off (the rarely useful default), you cannot use QCache as a direct substitute. One unelegant trick that works well in practice is to use QCache<QString, T *> instead of QCache<QString, T>. In that case, QCache owns the pointers, not the objects that the pointers refer to. For example,
            Q3Cache<QWidget> cache;
            cache.insert(widget->name(), widget);
            ...
            QWidget *foo = cache.take("foo");
            if (foo)
                foo->show();

    becomes

            typedef QWidget *QWidgetPtr;
            QCache<QString, QWidgetPtr> cache;
            cache.insert(widget->name(), new QWidgetPtr(widget));
            ...
            QWidgetPtr *ptr = cache.take("foo");
            if (ptr) {
                QWidget *foo = *ptr;
                delete ptr;
                foo->show();
            }

    An alternative is to stick to using Q3Cache.

QCacheIterator<T> has been renamed Q3CacheIterator<T> and moved to the Qt3Support library. The new QCache class doesn't offer any iterator types.

QCanvas

The canvas module classes have been renamed and moved to the Qt3Support library.

Qt 3 class nameCompatibility class in Qt 4
QCanvasQ3Canvas
QCanvasEllipseQ3CanvasEllipse
QCanvasItemQ3CanvasItem
QCanvasItemListQ3CanvasItemList
QCanvasLineQ3CanvasLine
QCanvasPixmapQ3CanvasPixmap
QCanvasPixmapArrayQ3CanvasPixmapArray
QCanvasPolygonQ3CanvasPolygon
QCanvasPolygonalItemQ3CanvasPolygonalItem
QCanvasRectangleQ3CanvasRectangle
QCanvasSplineQ3CanvasSpline
QCanvasSpriteQ3CanvasSprite
QCanvasTextQ3CanvasText
QCanvasViewQ3CanvasView

A replacement module for these classes, based on Qt 4's powerful painting system, is planned for release as part of Qt 4.2.

QColor

In Qt 4, QColor is a value type like QPoint or QRect. Graphics system-specific code has been implemented in QColorMap.

The numBitPlanes() function has been replaced by QColorMap::depth().

QColorGroup

In Qt 3, a QPalette consisted of three QColorGroup objects. In Qt 4, the (rarely used) QColorGroup abstraction has been eliminated. For source compatibility, a QColorGroup class is available when QT3_SUPPORT is defined.

The new QPalette still works in terms of color groups, specified through enum values (QPalette::Active, QPalette::Disabled, and QPalette::Inactive). It also has the concept of a current color group, which you can set using QPalette::setCurrentColorGroup().

The QPalette object returned by QWidget::palette() returns a QPalette initialized with the correct current color group for the widget. This means that if you had code like

    painter.setBrush(colorGroup().brush(QColorGroup::Background));

you can simply replace colorGroup() with palette():

    painter.setBrush(palette().brush(QPalette::Background));

QColorDrag

The QColorDrag class has been renamed Q3ColorDrag and moved to the Qt3Support library. In Qt 4, use QMimeData instead and call QMimeData::setColor() to set the color.

QComboBox

In Qt 3, the list box used to display the contents of a QComboBox widget could be accessed by using the listBox() function. In Qt 4, the standard list box is provided by a QListView widget, and can be accessed with the view() function.

See Virtual Functions for a list of QComboBox virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QCString

In Qt 3, QCString inherited from QByteArray. The main drawback of this approach is that the user had the responsibility of ensuring that the string is '\0'-terminated. Another important issue was that conversions between QCString and QByteArray often gave confusing results. (See the Achtung! Binary and Character Data article in Qt Quarterly for an overview of the pitfalls.)

Qt 4 solves that problem by merging the QByteArray and QCString classes into one class called QByteArray. Most functions that were in QCString previously have been moved to QByteArray. The '\0' issue is handled by having QByteArray allocate one extra byte that it always sets to '\0'. For example:

    QByteArray ba("Hello");
    ba.size();             // returns 5 (the '\0' is not counted)
    ba.length();           // returns 5
    ba.data()[5];          // returns '\0'

The Qt3Support library contains a class called Q3CString that inherits from the new QByteArray class and that extends it to provide an API that is as close to the old QCString class as possible. Note that the following functions aren't provided by Q3CString:

The following functions have lost their last parameter, which specified whether the search was case sensitive or not:

In both cases, the solution is to convert the QCString to a QString and use the corresponding QString functions instead.

Also be aware that QCString::size() (inherited from QByteArray) used to return the size of the character data including the '\0'-terminator, whereas the new QByteArray::size() is just a synonym for QByteArray::length(). This brings QByteArray in line with QString.

When porting to Qt 4, occurrences of QCString should be replaced with QByteArray or QString. The following table summarizes the API differences between the Q3CString class and the Qt 4 QByteArray and QString classes:

Q3CString functionQt 4 equivalent
Q3CString::Q3CString(const char *, uint)See remark below
Q3CString::Q3CString(int)QByteArray::QByteArray(int, char)
Q3CString::leftJustify()QString::leftJustified()
Q3CString::length()QByteArray::length() or QByteArray::size() (equivalent)
Q3CString::lower()QByteArray::toLower()
Q3CString::rightJustify()QString::rightJustified()
Q3CString::setExpand()See remark below
Q3CString::simplifyWhiteSpace()QByteArray::simplified()
Q3CString::sprintf()QString::sprintf()
Q3CString::stripWhiteSpace()QByteArray::trimmed()
Q3CString::toDouble()QString::toDouble()
Q3CString::toFloat()QString::toFloat()
Q3CString::toInt()QString::toInt()
Q3CString::toLong()QString::toLong()
Q3CString::toShort()QString::toShort()
Q3CString::toUInt()QString::toUInt()
Q3CString::toULong()QString::toULong()
Q3CString::toUShort()QString::toUShort()
Q3CString::upper()QByteArray::toUpper()

Remarks:

  1. Q3CString(const char *str, uint max) constructs a string of length strlen(str) or max - 1, whichever is shorter. QByteArray(const char *data, int size) constructs a byte array containing exactly size bytes.

    For example, if you have code like

            QCString str1("Hello", 4);           // "Hel"
            QCString str2("Hello world!", n);

    you can rewrite it as

            QByteArray str1("Hello", 3);
            QByteArray str2("Hello world!");
            str2.truncate(n - 1);
  2. Q3CString::setExpand(uint index, char ch) has no equivalent in Qt 4.

    For example, if you have code like

            QCString str("Hello world");
            str.setExpand(16, '\n');            // "Hello world     \n"

    you can rewrite it as

            QByteArray str("Hello world");
            while (str.size() < 16)
                str += ' ';
            str += '\n';

Since the old QCString class inherited from QByteArray, everything that is said in the QByteArray section applies for QCString as well.

QCustomEvent

In Qt 3, developers could create a custom event by constructing a new QCustomEvent, and send relevant data to other components in the application by passing a void pointer, either on construction or using the setData() function. Objects could receive custom events by reimplementing the customEvent() function, and access the stored data using the event's data() function.

In Qt 4, custom events are created by subclassing QEvent and reimplementing the type() function to return a value in the range allocated for user events. Event-specific data can be stored in a way that is appropriate for your application. Custom events are still delivered to each object's customEvent() handler function, but as QEvent objects rather than as deprecated QCustomEvent objects.

QDataBrowser

The QDataBrowser class has been renamed Q3DataBrowser and moved to the Qt3Support library. It is expected that Qt 4.1 will offer a replacement class. In the meantime, you can use Q3DataBrowser for creating data-aware forms or you can roll your own.

See QtSql Module for an overview of the new SQL classes.

QDataPump

The QDataPump class was used internally in Qt 2.x in conjunction with QImageConsumer. It was obsoleted in Qt 3.0.

    If you use this mechanism in your application, please submit a
    report to the \l{Task Tracker} on the Trolltech
    website and we will try to find a satisfactory substitute.

QDataSink

The QDataSink class was used internally in Qt 2.x in conjunction with QImageConsumer. It was obsoleted in Qt 3.0.

    If you use this mechanism in your application, please submit a
    report to the \l{Task Tracker} on the Trolltech
    website and we will try to find a satisfactory substitute.

QDataSource

The QDataSource class was used internally in Qt 2.x in conjunction with QImageConsumer. It was obsoleted in Qt 3.0.

    If you use this mechanism in your application, please submit a
    report to the \l{Task Tracker} on the Trolltech
    website and we will try to find a satisfactory substitute.

QDataTable

The QDataTable class has been renamed Q3DataTable and moved to the Qt3Support library. It is expected that Qt 4.1 will offer a replacement class. In the meantime, you can use Q3DataTable for creating data-aware forms or you can roll your own.

See QtSql Module for an overview of the new SQL classes.

QDataView

The QDataView class has been renamed Q3DataView and moved to the Qt3Support library. It is expected that Qt 4.1 will offer a replacement class. In the meantime, you can use Q3DataTable for creating data-aware forms or you can roll your own.

See QtSql Module for an overview of the new SQL classes.

QDateEdit

The QDateEdit class in Qt 4 is a convenience class based on QDateTimeEdit. The old class has been renamed Q3DateEdit and moved to the Qt3Support library.

See Virtual Functions for a list of QDateEdit virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QDateTimeEditBase

The QDateTimeEditBase class has been renamed Q3DateTimeEditBase and moved to Qt3Support. Use QDateTimeEdit or QAbstractSpinBox instead.

QDateTimeEdit

The old QDateTimeEdit class has been renamed Q3DateTimeEditBase and moved to Qt3Support. The new QDateTimeEdit in Qt 4 has been rewritten from scratch to provide a more flexible and powerful API.

See Virtual Functions for a list of QDateTimeEdit virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QDeepCopy<T>

The QDeepCopy<T> class in Qt 3 provided a means of ensuring that implicitly shared and explicitly shared classes referenced unique data. This was necessary because the reference counting in Qt's container classes was done in a thread-unsafe manner.

With Qt 4, QDeepCopy<T> has been renamed Q3DeepCopy<T> and moved to the Qt3Support library. Removing it from existing code is straightforward.

For example, if you have code like

    QString str1 = "I am a string";
    QDeepCopy<QString> str2 = str1;
    QString str3 = QDeepCopy<QString>(str2);

you can rewrite it as

    QString str1 = "I am a string";
    QString str2 = str1;
    QString str3 = str2;

QDial

See Virtual Functions for a list of QComboBox virtual member functions in Qt 3 that are no longer virtual in Qt 4.

See Properties for a list of QDial properties in Qt 3 that have changed in Qt 4.

QDict<T>

QDict<T> has been renamed Q3Dict<T> and moved to Qt3Support. It has been replaced by the more modern QHash<Key, T> and QMultiHash<Key, T> classes.

When porting old code that uses QDict<T> to Qt 4, there are four classes that you can use:

Qt 4 classWhen to use it
QMultiHash<QString, T *>Since Q3Dict<T> is pointer-based and allows duplicate keys, this is usually the most straightforward conversion.
QMultiHash<QString, T>If type T is an assignable data type, you can use T as the value type rather than T *. This often leads to nicer code.
QHash<QString, T *>If you don't use duplicate keys, you can use QHash instead of QMultiHash. QMultiHash inherits from QHash.
QHash<QString, T>

The APIs of Q3Dict<T> and QMultiHash<QString, T *> are quite similar. The main issue is that Q3Dict supports auto-delete whereas QMultiHash doesn't.

The following table summarizes the API differences between the two classes:

Q3Dict functionQMultiHash equivalent
Q3Dict::Q3Dict(int size, bool caseSensitive)See remarks below
Q3Dict::autoDelete()N/A
Q3Dict::count()QMultiHash::count() or QMultiHash::size() (equivalent)
Q3Dict::find(const QString &)QMultiHash::value(const QString &)
Q3Dict::remove(const QString &)QMultiHash::take(const QString &)
Q3Dict::resize(uint)QMultiHash::reserve(int)
Q3Dict::setAutoDelete()See discussion below
Q3Dict::size()QMultiHash::capacity()
Q3Dict::statistics()N/A
Q3Dict::operator[](const QString &)See remark below

Remarks:

  1. Q3Dict requires the user to allocate a specific number of buckets by passing a prime number (17 by default) to the constructor and/or calling Q3Dict::resize() later on. In contrast, QMultiHash's hash table automatically grows and shrinks as needed, and the constructor doesn't take a prime number.
  2. Q3Dict supportes case-insensitive lookups by passing false as second argument to the constructor. This feature has no equivalent in QMultiHash. Instead, call QString::toLower() before you insert or lookup a key in the hash.
  3. Q3Dict::size() and QMultiHash::size() have different semantics. The former returns the number of buckets in the container, whereas the latter returns the number of items in the container.
  4. If there are multiple items with the same key, Q3Dict::remove() removes only the most recently inserted item, whereas QMultiHash::remove() removes all items that share a particular key. To remove only the most recently inserted item, call QMultiHash::take().
  5. Q3Dict has only one [] operator (Q3Dict::operator[]()), providing const access to an item's value. QMultiHash also has a non-const overload that can be used on the left side of the assignment operator. If you use the [] operator on a non-const QHash with an unexisting item, QHash will created an element and initialize it to be a null pointer. For that reason, Q3Dict::operator[] should be converted to QMultiHash::value(), not QMultiHash::operator[].

If you use Q3Dict's auto-delete feature (by calling Q3Dict::setAutoDelete(true)), you need to do some more work. You have two options: Either you call delete yourself whenever you remove an item from the container, or you use QMultiHash<QString, T> instead of QMultiHash<QString, T *> (i.e. store values directly instead of pointers to values). Here, we'll see when to call delete.

The following table summarizes the idioms that you need to watch out for if you want to call delete yourself.

Q3Dict idiomQMultiHash idiom
    dict.replace(key, value);
    delete hash.take(key);
    hash.insert(key, value);
    dict.remove(key, value);
    delete hash.take(key);
    dict.clear();

(also called from Q3Dict's destructor)

    while (!hash.isEmpty()) {
        T *value = *hash.begin();
        dict.erase(hash.begin());
        delete value;
    }

In 99% of cases, the following idiom also works:

    qDeleteAll(hash);
    hash.clear();

However, it may lead to crashes if hash is referenced from the value type's destructor, because hash contains dangling pointers until clear() is called.

Be aware that Q3Dict's destructor automatically calls clear(). If you have a Q3Dict data member in a custom class and use the auto-delete feature, you will need to call delete on all the items in the container from your class destructor to avoid a memory leak.

Finally, QDictIterator<T> (renamed Q3DictIterator<T>) must also be ported. There are no fewer than four iterator classes that can be used as a replacement: QHash::const_iterator, QHash::iterator, QHashIterator, and QMutableHashIterator. The most straightforward class to use when porting is QHashIterator<QString, T *>. The following table summarizes the API differences:

Q3DictIterator functionsQt 4 equivalent
Q3DictIterator::count()QHash::count() or QHash::size()
Q3DictIterator::current()QHashIterator::value()
Q3DictIterator::currentKey()QHashIterator::key()
Q3DictIterator::isEmpty()QHash::isEmpty()
Q3DictIterator::toFirst()QHashIterator::toFront()
Q3DictIterator::operator()()QHashIterator::value()
Q3DictIterator::operator*()QHashIterator::value()
Q3DictIterator::operator++()See remark below

Be aware that QHashIterator has a different way of iterating than Q3DictIterator. A typical loop with Q3DictIterator looks like this:

    Q3DictIterator<QWidget> i(dict);
    while (i.current() != 0) {
        do_something(i.currentKey(), i.current());
        ++i;
    }

Here's the equivalent QHashIterator loop:

    QHashIterator<QString, QWidget *> i(hash);
    while (i.hasNext()) {
        i.next();                   // must come first
        do_something(i.key(), i.value());
    }

See Java-style iterators for details.

QDir

The following functions used to have a boolean acceptAbsPath parameter that defaulted to true:

In Qt 3, if acceptAbsPath is true, a file name starting with '/' is be returned without change; if acceptAbsPath is false, an absolute path is prepended to the file name. For example:

Current directoryFile nameacceptAbsPathFile path
/home/tsmithindex.htmltrue/home/tsmith/index.html
false/home/tsmith/index.html
/home/tsmith/index.htmltrue/index.html
false/home/tsmith/index.html

In Qt 4, this parameter is no longer available. If you use it in your code, you can check that QDir::isRelativePath() returns false instead.

For example, if you have code like

    QDir dir("/home/tsmith");
    QString path = dir.filePath(fileName, false);

you can rewrite it as

    QDir dir("/home/tsmith");
    QString path;
    if (dir.isRelativePath(fileName))
        path = dir.filePath(fileName);
    else
        path = fileName;

QDir::encodedEntryList() has been removed.

fileInfoList(), entryInfoList(), and drives() now return a QList<QFileInfo> and not a QPtrList<QFileInfo> *. Code using these methods will not work with the Qt3Support library and must be adapted instead.

See Virtual Functions for a list of QDir virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QDir::match() now always matches case insensitively.

QDir::homeDirPath() has been removed. Use QDir::home() instead, and extract the path separately.

QDns

Qt 3 used its own implementa