Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

Porting GuidesPorting to Qt 4 - Virtual Functions

Contents

Porting to Qt 4

This document describes the process of 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 thekey features offered by Qt 4. See alsoMoving from Qt 3 to Qt 4 for tips on how to write Qt 3 code that is easy to port to Qt 4.

Other porting guides:

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 completelysource 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 requires some effort, but once completed the considerable additional power and flexibility of Qt 4 is 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 lineQT += qt3support to your.pro file if you useqmake; otherwise, edit your makefile or project file to link against theQt3Support library and add-DQT3_SUPPORT to your compiler flags. (You might also need to specify other libraries. SeeWhat's New in Qt 4 for details.)
  4. Run theqt3to4 porting tool. The tool will go through your source code and adapt it to Qt 4.
  5. Follow the instructions in thePorting 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.

Theqt3to4 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 intoQ3ListBox.

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 theQt3Support classes (such asQ3Action,Q3ListBox, andQ3ValueList), Qt 4 provides compatibility functions when it's possible for an old API to cohabit with the new one. For example,QString provides aQString::simplifyWhiteSpace() compatibility function that's implemented inline and that simply callsQString::simplified().The compatibility functions are not documented here; instead, they are documented for each class.

If you have the lineQT += qt3support in your.pro file,qmake will automatically define theQT3_SUPPORT symbol, turning on compatibility function support. You can also define the symbol manually (e.g., if you don't want to link against theQt3Support library), or you can defineQT3_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 theqt-interest mailing list. If you are a licensed customer, you can also contact Qt's technical support team.

Table of contents:

Casting and Object Types

In Qt 3, it was possible to use theqt_cast() function to determine whether instances ofQObject subclasses could be safely cast to derived types of those subclasses. For example, if aQFrame instance is passed to a function whose signature specifies aQWidget pointer as its argument,qt_cast() could be used to obtain aQFrame pointer so that the instance's functions can be accessed.

In Qt 4, much of this functionality is provided by theqobject_cast() function, and additional functions also provide similar functionality for certain non-QObject types:

Type Names

The table below lists the classes that have been renamed in Qt 4. If you compile your applications withQT3_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. Theqt3to4 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 withQT3_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. Theqt3to4 tool 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 withQT3_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. Theqt3to4 tool performs the conversion automatically.

Qt 3 enum value nameQt 4 enum value name
IO_AppendQIODevice::Append
IO_ReadOnlyQIODevice::ReadOnly
IO_ReadWriteQIODevice::ReadWrite
IO_TranslateQIODevice::Text
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 followingwindow flags have been either replaced withwidget attributes or have been deprecated:

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

Qt 3 typeQt 4 equivalent
Qt::WShowModalUseQWidget::setWindowModality(Qt::ApplicationModal) instead.
Qt::WGroupLeaderUseQWidget::setWindowModality(Qt::WindowModal) 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'scaption property has been renamedwindowTitle 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 theQ_PROPERTY() macro, removing the need for aQ_OVERRIDE() macro.

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

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 byQt 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:

Some properties have been removed from Qt 4, but the associated access functions are provided ifQT3_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. Note that this only applies to the properties of theQt3Support library, i.e.QT3_SUPPORT properties of the other libraries must be ported manually when converting Qt 3 UI files to Qt 4.

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::autoResizeCallQWidget:setFixedSize(QWidget::sizeHint()) whenever you change the contents.
QButton::exclusiveToggleSeeQAbstractButton::autoExclusive.
QButton::pixmapUseQAbstractButton::icon instead.
QButton::toggleStateUseQCheckBox::setState() andQCheckBox::state() instead.
QButton::toggleTypeUseQCheckBox::setTristate() instead.
QComboBox::autoResizeCallQWidget:setFixedSize(QWidget::sizeHint()) whenever you change the contents.
QFrame::contentsRectUseQ3Frame::contentsRect() instead.
QFrame::marginUseQWidget::setContentsMargins() instead.
QTabBar::keyboardFocusTabN/A
QToolButton::offIconSetUse theoff component ofQAbstractButton::icon instead.
QToolButton::onIconSetUse theon component ofQAbstractButton::icon instead.
QWidget::microFocusHintN/A
QMimeSource::serialNumber ()N/A

Explicit Sharing

Qt 4 is the first version of Qt that contains noexplicitly shared classes. All classes that were explicitly shared in Qt 3 areimplicitly 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.)

Painting and Redrawing Widgets

When implementing custom widgets in Qt 3, it was possible to useQPainter to draw on a widget outside paint events. This made it possible to integrate Qt applications with third party libraries and tools that impose their own rendering models. For example, a widget might be repainted in a slot using data obtained from an external source.

In Qt 4, it is only possible to paint on a widget from within itspaintEvent() handler function. This restriction simplifies Qt's interaction with native window systems, improves the performance of applications by reducing the number of redraw operations, and also enables features to be implemented to improve the appearance of widgets, such as a backing store.

Generally, we recommend redesigning applications to perform all painting operations inpaintEvent() functions, deferring actual painting until the next time this function is called. Applications can post paint events to trigger repaints, and it may be possible to examine your widget's internal state to determine which part of the widget needs to be repainted.

If asynchronous repaints are used extensively by your application, and it is not practical to redesign the rendering model to perform all painting operations from within a widget'spaintEvent() function, it may be necessary to consider using an intermediate painting step. In this approach, one or more images can be updated asynchronously and painted on the widget in the paint event. To avoid excessive buffering, it may be worthwhile disabling the backing store by setting the widget'sQt::WA_PaintOnScreen widget attribute.

On certain platforms, theQt::WA_PaintOutsidePaintEvent widget attribute can be set to allow a widget to be painted from outside paint events.

Note:Setting widget attributes to disable key features of Qt's widget rendering model may also cause other features to be disabled.

Compatibility Signals and Slots

WhenQT3_SUPPORT is defined, the default connection type for signals and slots is theQt::AutoCompatConnection type. This allows so-calledcompatibility signals and slots (defined in Qt 3 support mode to provide Qt 3 compatibility features) to be connected to other signals and slots.

However, if Qt is compiled with debugging output enabled, and the developer uses other connection types to connect to compatibility signals and slots (perhaps by building their application without Qt 3 support enabled), then Qt will output warnings to the console to indicate that compatibility connections are being made. This is intended to be used as an aid in the process of porting a Qt 3 application to Qt 4.

QAccel

TheQAccel class has been renamedQ3Accel and moved to theQt3Support module. In new applications, you have three options:

  1. You can useQAction and set a key sequence usingQAction::setShortcut().
  2. You can useQShortcut, a class that provides similar functionality toQ3Accel.
  3. You can useQWidget::grabShortcut() and process "shortcut" events by reimplementingQWidget::event().

TheQ3Accel class also supports multiple accelerators using the same object, by callingQ3Accel::insertItem() multiple times. In Qt 4, the solution is to create multipleQShortcut objects.

QAccessibleInterface

TheQAccessibleInterface 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 inheritQAccessibleInterface or one of its subclasses (QAccessibleObject,QAccessibleWidget, etc.), you must port them the newQAccessibleInterface API.

SeeVirtual Functions for a list ofQAccessibleInterface virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QAccessibleTitleBar

TheQAccessibleTitleBar has been renamed Q3AccessibleTitleBar and moved to theQt3Support library.

QAction

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

The oldQAction andQActionGroup classes have been renamedQ3Action andQ3ActionGroup and moved toQt3Support. In addition, the newQAction class has compatibility functions to ease transition to Qt 4. Note that when usingQ3ToolBar andQ3PopupMenu, their actions must beQ3Actions.

SeeVirtual Functions for a list ofQAction virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QActionGroup

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

QApplication

TheQApplication class has been split into two classes:QCoreApplication andQApplication. The newQApplication class inheritsQCoreApplication 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() andQApplication::topLevelWidgets() used to return a pointer to aQWidgetList. Now they return aQWidgetList.

    Also,QWidgetList has changed from being a typedef for QPtrList<QWidget> to being a typedef forQList<QWidget *>. See thesection 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

TheQAquaStyle class first appeared in Qt 3.0, when the Qt for Mac OS X port was first released. It emulated Apple's "Aqua" theme. In Qt 3.1,QAquaStyle was obsoleted byQMacStyle, which uses Appearance Manager to perform its drawing.

TheQAquaStyle class is no longer provided in Qt 4. UseQMacStyle instead.

QAsciiCache<T>

QAsciiCache<T> has been renamedQ3AsciiCache<T> and moved to theQt3Support library. It has been replaced byQCache<QByteArray, T>.

For details, read thesection on QCache<T>, mentally substitutingQByteArray forQString.

QAsciiDict<T>

QAsciiDict<T> and QAsciiDictIterator<T> have been renamedQ3AsciiDict<T> andQ3AsciiDictIterator<T> and moved to theQt3Support library. They have been replaced by the more modernQHash<Key, T> andQMultiHash<Key, T> classes and their associated iterator classes.

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

For details, read thesection on QDict<T>, mentally substitutingQByteArray forQString.

QAsyncIO

TheQAsyncIO 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 theTask Tracker on the Qt website and we will try to find a satisfactory substitute.

QBackInsertIterator

The undocumentedQBackInsertIterator 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 fromQByteArray. In Qt 4,QBitArray is a totally independent class. This makes very little difference to the user, except that the newQBitArray doesn't provide any ofQByteArray's byte-based API anymore. These calls will result in a compile-time error, except calls toQBitArray::truncate(), whose parameter was a number ofbytes in Qt 3 and a number of bits in Qt 4.

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

TheQBitVal class has been renamed QBitRef.

QButton

TheQButton class has been replaced byQAbstractButton in Qt 4. Classes likeQPushButton andQRadioButton inherit fromQAbstractButton. As a help when porting older Qt applications, theQt3Support library contains aQ3Button class implemented in terms of the newQAbstractButton.

If you used theQButton class as a base class for your own button type and want to port your code to the newerQAbstractButton, you need to be aware thatQAbstractButton has no equivalent for theQ3Button::drawButton(QPainter *) virtual function. The solution is to reimplementQWidget::paintEvent() in yourQAbstractButton subclass as follows:

void MyButton::paintEvent(QPaintEvent*){QPainter painter(this);    drawButton(&painter);}
Q3Button functionQAbstractButton equivalent
Q3Button::autoResize()CallQWidget:setFixedSize(QWidget::sizeHint()) whenever you change the contents.
Q3Button::isExclusiveToggle()UseQAbstractButton::group() orQAbstractButton::autoExclusive() instead.
Q3Button::pixmap() constQAbstractButton::icon()
Q3Button::setAutoResize()N/A
Q3Button::setPixmap(constQPixmap &)QAbstractButton::setIcon(constQIcon &)
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 newQAbstractButton class doesn't support "tristate" directly; this feature is implemented inQCheckBox instead. The two other "toggle types" (QButton::SingleShot andQButton::Toggle) are replaced by aQAbstractButton::checkable property.
  2. In Qt 3,QButton had a "toggle state", which could beQButton::Off,QButton::NoChange, orQButton::On. In Qt 4, this mechanism has been moved toQCheckBox.

SeeVirtual Functions for a list ofQButton virtual member functions in Qt 3 that aren't virtual in Qt 4.

SeeProperties for a list ofQButton properties in Qt 3 that have changed in Qt 4.

QButtonGroup

TheQButtonGroup class has been completely redesigned in Qt 4. For compatibility, the oldQButtonGroup class has been renamedQ3ButtonGroup and has been moved toQt3Support. Likewise, theQHButtonGroup andQVButtonGroup convenience subclasses have been renamedQ3HButtonGroup andQ3VButtonGroup and moved to theQt3Support library.

The oldQButtonGroup, as well asQ3ButtonGroup, 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. AQ3ButtonGroup can display a frame and a title because it inheritsQ3GroupBox.
  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, usingQ3ButtonGroup::insert(), into the button group and given an ID number.

UnlikeQ3ButtonGroup, the newQButtonGroup doesn't inheritQWidget. It is very similar to a "hiddenQ3ButtonGroup".

If you use aQ3ButtonGroup,Q3HButtonGroup, orQ3VButtonGroup as a widget and want to port to Qt 4, you can replace it withQGroupBox. 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 thesection on QGroupBox below.

SeeVirtual Functions for a list ofQButtonGroup 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 ofQString.

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

  1. The QMemArray(int size) constructor has been replaced withQByteArray(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 newQByteArray::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 renamedQByteArray::count(char). In addition, there now exists aQByteArray::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 newQByteArray 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 useQByteArray::fromRawData() and to call free() yourself to avoid a memory leak, or to use theQByteArray(const char *, int) constructor, which will take a deep copy of the data.
  5. QMemArray::bsearch() and QMemArray::sort() have no equivalent in the newQByteArray class. UseqBinaryFind() andqSort() if you need that functionality.

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

QCache<T>

QCache<T> has been renamedQ3Cache<T> and moved toQt3Support. The newQCache 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 forQ3Cache<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() orQCache::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 newQCache'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 inQMultiHash. Instead, callQString::toLower() before you insert or lookup a key in the hash.
  3. TheQ3Cache::insert() function returns abool 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 newQCache::insert() function returnsvoid 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 newQCache classalways takes ownership of the items it stores (i.e. auto-delete is always on). If you useQ3Cache with auto-delete turned off (the rarely useful default), you cannot useQCache as a direct substitute. One unelegant trick that works well in practice is to useQCache<QString, T *> instead ofQCache<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

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

    An alternative is to stick to usingQ3Cache.

QCacheIterator<T> has been renamedQ3CacheIterator<T> and moved to theQt3Support library. The newQCache class doesn't offer any iterator types.

QCanvas

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

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

TheGraphics View Framework replacesQCanvas. For more on porting to Graphics View, seePorting to Graphics View.

QColor

In Qt 4,QColor is a value type likeQPoint orQRect. Graphics system-specific code has been implemented inQColormap.

TheQColor::maxColors() function has been replaced byQColormap::size().

TheQColor::numBitPlanes() function has been replaced byQColormap::depth().

TheQColor::setNamedColor() function no longer supports the named color in the same way as Qt 3. Qt 4'ssetNamedColor() uses the new W3C convention as statedhere.

The predefined colors listed in the table above were staticQColor objects in Qt 3. In Qt 4, they are enum values of typeQt::GlobalColor. Thanks to the implicitQColor(Qt::GlobalColor) constructor, the enum values are automatically converted toQColors in most contexts. Occasionally, you might need a cast.

For example, if you have code like

QColor lightCyan = Qt::cyan.light(180);

you can rewrite it as

QColor lightCyan=QColor(Qt::cyan).light(180);

QColorGroup

In Qt 3, aQPalette consisted of threeQColorGroup objects. In Qt 4, the (rarely used)QColorGroup abstraction has been eliminated. For source compatibility, aQColorGroup class is available whenQT3_SUPPORT is defined.

The newQPalette still works in terms of color groups, specified through enum values (QPalette::Active,QPalette::Disabled, andQPalette::Inactive). It also has the concept of acurrent color group, which you can set usingQPalette::setCurrentColorGroup().

TheQPalette object returned byQWidget::palette() returns aQPalette initialized with the correct current color group for the widget. This means that if you had code like

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

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

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

QColorDrag

TheQColorDrag class has been renamedQ3ColorDrag and moved to theQt3Support library. In Qt 4, useQMimeData instead and call QMimeData::setColor() to set the color.

QComboBox

In Qt 3, the list box used to display the contents of aQComboBox widget could be accessed by using thelistBox() function. In Qt 4, the standard list box is provided by aQListView widget, and can be accessed with theview() function.

SeeVirtual Functions for a list ofQComboBox virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QCString

In Qt 3,QCString inherited fromQByteArray. 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 betweenQCString andQByteArray often gave confusing results. (See theAchtung! Binary and Character Data article inQt Quarterly for an overview of the pitfalls.)

Qt 4 solves that problem by merging theQByteArray andQCString classes into one class calledQByteArray. Most functions that were inQCString previously have been moved toQByteArray. The '\0' issue is handled by havingQByteArray 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 5ba.data()[5];// returns '\0'

TheQt3Support library contains a class calledQ3CString that inherits from the newQByteArray class and that extends it to provide an API that is as close to the oldQCString class as possible. Note that the following functions aren't provided byQ3CString:

  • QCString::find(constQRegExp &, int)
  • QCString::findRev(constQRegExp &, int)
  • QCString::contains(constQRegExp &)
  • QCString::replace(constQRegExp &, const char *)

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 theQCString to aQString and use the correspondingQString functions instead.

Also be aware thatQCString::size() (inherited fromQByteArray) used to return the size of the character dataincluding the '\0'-terminator, whereas the newQByteArray::size() is just a synonym forQByteArray::length(). This bringsQByteArray in line withQString.

When porting to Qt 4, occurrences ofQCString should be replaced withQByteArray orQString. The following table summarizes the API differences between theQ3CString class and the Qt 4QByteArray andQString 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() orQByteArray::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) ormax - 1, whichever is shorter.QByteArray(const char *data, int size) constructs a byte array containing exactlysize 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 oldQCString class inherited fromQByteArray, everything that is said in theQByteArray section applies forQCString as well.

QCustomEvent

In Qt 3, developers could create a custom event by constructing a newQCustomEvent, 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 thecustomEvent() function, and access the stored data using the event's data() function.

In Qt 4, custom events are created by subclassingQEvent. Event-specific data can be stored in a way that is appropriate for your application. Custom events are still delivered to each object'scustomEvent() handler function, but asQEvent objects rather than as deprecatedQCustomEvent objects.

QDataBrowser

TheQDataBrowser class has been renamedQ3DataBrowser and moved to theQt3Support library. In Qt 4.2, you should use theQDataWidgetMapper class to create data-aware forms.

SeeQtSql Module for an overview of the new SQL classes.

QDataPump

TheQDataPump 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 theTask Tracker on the Qt website and we will try to find a satisfactory substitute.

QDataSink

TheQDataSink 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 theTask Tracker on the Qt website and we will try to find a satisfactory substitute.

QDataSource

TheQDataSource 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 theTask Tracker on the Qt website and we will try to find a satisfactory substitute.

QDataTable

TheQDataTable class has been renamedQ3DataTable and moved to theQt3Support library. In Qt 4.2, you should use theQDataWidgetMapper class to create data-aware forms.

SeeQtSql Module for an overview of the new SQL classes.

QDataView

TheQDataView class has been renamedQ3DataView and moved to theQt3Support library. In Qt 4.2, you should use theQDataWidgetMapper class to create data-aware forms.

SeeQtSql Module for an overview of the new SQL classes.

QDateEdit

TheQDateEdit class in Qt 4 is a convenience class based onQDateTimeEdit. The old class has been renamedQ3DateEdit and moved to theQt3Support library.

SeeVirtual Functions for a list ofQDateEdit virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QDateTimeEditBase

TheQDateTimeEditBase class has been renamedQ3DateTimeEditBase and moved toQt3Support. UseQDateTimeEdit orQAbstractSpinBox instead.

QDateTimeEdit

The oldQDateTimeEdit class has been renamedQ3DateTimeEditBase and moved toQt3Support. The newQDateTimeEdit in Qt 4 has been rewritten from scratch to provide a more flexible and powerful API.

SeeVirtual Functions for a list ofQDateTimeEdit virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QDeepCopy<T>

TheQDeepCopy<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 renamedQ3DeepCopy<T> and moved to theQt3Support 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

SeeVirtual Functions for a list ofQDial virtual member functions in Qt 3 that are no longer virtual in Qt 4.

SeeProperties for a list ofQDial properties in Qt 3 that have changed in Qt 4.

QDict<T>

QDict<T> has been renamedQ3Dict<T> and moved toQt3Support. It has been replaced by the more modernQHash<Key, T> andQMultiHash<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 *>SinceQ3Dict<T> is pointer-based and allows duplicate keys, this is usually the most straightforward conversion.
QMultiHash<QString, T>If typeT is anassignable data type, you can useT as the value type rather thanT *. This often leads to nicer code.
QHash<QString, T *>If you don't use duplicate keys, you can useQHash instead ofQMultiHash.QMultiHash inherits fromQHash.
QHash<QString, T>

The APIs ofQ3Dict<T> andQMultiHash<QString, T *> are quite similar. The main issue is thatQ3Dict supports auto-delete whereasQMultiHash 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() orQMultiHash::size() (equivalent)
Q3Dict::find(constQString &)QMultiHash::value(constQString &)
Q3Dict::remove(constQString &)QMultiHash::take(constQString &)
Q3Dict::resize(uint)QMultiHash::reserve(int)
Q3Dict::setAutoDelete()See discussion below
Q3Dict::size()QMultiHash::capacity()
Q3Dict::statistics()N/A
Q3Dict::operator[](constQString &)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 callingQ3Dict::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 inQMultiHash. Instead, callQString::toLower() before you insert or lookup a key in the hash.
  3. Q3Dict::size() andQMultiHash::size() have different semantics. The former returns the number of buckets in the container, whereas the latter returns the number ofitems in the container.
  4. If there are multiple items with the same key,Q3Dict::remove() removes only the most recently inserted item, whereasQMultiHash::remove() removes all items that share a particular key. To remove only the most recently inserted item, callQMultiHash::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-constQHash 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 toQMultiHash::value(), not QMultiHash::operator[].

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

The following table summarizes the idioms that you need to watch out for if you want to calldelete 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 fromQ3Dict's destructor)

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

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

qDeleteAll(hash);hash.clear();

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

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

Finally,QDictIterator<T> (renamedQ3DictIterator<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, andQMutableHashIterator. The most straightforward class to use when porting isQHashIterator<QString, T *>. The following table summarizes the API differences:

Be aware thatQHashIterator has a different way of iterating thanQ3DictIterator. A typical loop withQ3DictIterator looks like this:

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

Here's the equivalentQHashIterator loop:

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

SeeJava-style iterators for details.

QDir

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

In Qt 3, ifacceptAbsPath is true, a file name starting with '/' is be returned without change; ifacceptAbsPath 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 thatQDir::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 aQList<QFileInfo> and not a QPtrList<QFileInfo> *. Code using these methods will not work with theQt3Support library and must be adapted instead.

SeeVirtual Functions for a list ofQDir 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. UseQDir::home() instead, and extract the path separately.

QDns

Qt 3 used its own implementation of the DNS protocol and provided a low-levelQDns class. Qt 4'sQHostInfo class uses the system'sgethostbyname() function from a thread instead.

The oldQDns class has been renamedQ3Dns and moved to theQt3Support library. The newQHostInfo class has a radically different API: It consists mainly of two static functions, one of which is blocking (QHostInfo::fromName()), the other non-blocking (QHostInfo::lookupHost()). See theQHostInfo class documentation for details.

QDockArea

TheQDockArea class has been renamedQ3DockArea and moved to theQt3Support library. In Qt 4,QMainWindow handles the dock and toolbar areas itself. See theQMainWindow documentation for details.

QDockWindow

The oldQDockWindow class has been renamedQ3DockWindow and moved to theQt3Support library. In Qt 4, there is a newQDockWidget class with a different API. See the class documentation for details.

SeeVirtual Functions for a list ofQDockWidget virtual member functions in Qt 3 that are no longer virtual in Qt 4.

Note:Q3DockWindow'shorizontallyStretchable property can be achieved inQDockWidget withsize policies.

QDragObject

TheQDragObject class has been renamedQ3DragObject and moved to theQt3Support library. In Qt 4, it has been replaced by theQMimeData class. See the class documentation for details.

Note that theQ3DragObject::DragCopyOrMove drag and drop mode is interpreted differently to Qt 3's QDragObject::DragCopyOrMove mode. In Qt 3, a move operation was performed by default, and the user had to hold down theCtrl key to perform a copy operation. In Qt 4, a copy operation is performed by default; the user has to hold down theShift key to perform a move operation.

SeePorting to Qt 4 - Drag and Drop for a comparison between the drag and drop APIs in Qt 3 and Qt 4.

QDropSite

TheQDropSite class has been renamedQ3DropSite and moved to theQt3Support library.

TheQDropSite class has been obsolete ever since Qt 2.0. The only thing it does is callQWidget::setAcceptDrops(true).

For example, if you have code like

class MyWidget : public QWidget, public QDropSite{public:    MyWidget(const QWidget *parent)        : QWidget(parent), QDropSite(this)    {    }    ...}

you can rewrite it as

class MyWidget :publicQWidget{public:    MyWidget(constQWidget*parent)        :QWidget(parent)    {        setAcceptDrops(true);    }...}

SeePorting to Qt 4 - Drag and Drop for a comparison between the drag and drop APIs in Qt 3 and Qt 4.

QEditorFactory

TheQEditorFactory class has been renamedQ3EditorFactory and moved to theQt3Support library.

SeeQtSql Module for an overview of the new SQL classes.

QEventLoop

In Qt 3,QEventLoop combined the Qt event loop and the event dispatching. In Qt 4, these tasks are now assigned to two distinct classes:QEventLoop andQAbstractEventDispatcher.

If you subclassedQEventLoop to integrate with another library's event loop, you must subclassQAbstractEventDispatcher instead. See the class documentation for details.

Developers usingQEventLoop::loopLevel() in Qt 3 should use QCoreApplication::loopLevel() instead. Note that this function is marked as obsolete, but it is expected to be available for the lifetime of Qt 4.

QFileDialog

TheQFileDialog class in Qt 4 has been totally rewritten. It provides most of the functionality of the oldQFileDialog class, but with a different API. Some functionality, such as the ability to preview files, is expected to be added in a later Qt 4 release.

The oldQFileDialog,QFileIconProvider, andQFilePreview classes has been renamedQ3FileDialog,Q3FileIconProvider, andQ3FilePreview and have been moved toQt3Support. You can use them if you need some functionality not provided yet by the newQFileDialog class.

The following table lists which functions have been renamed or removed in Qt 4.

Old functionQt 4 equivalent
Q3FileDialog::addFilter(constQString &)See remark below
Q3FileDialog::addLeftWidget(QWidget *)N/A
Q3FileDialog::addRightWidget(QWidget *)N/A
Q3FileDialog::addToolButton(QAbstractButton *, bool separator)N/A
Q3FileDialog::addWidgets(QLabel *,QWidget *,QPushButton *)N/A
Q3FileDialog::dir()QFileDialog::directory()
Q3FileDialog::dirPath()QFileDialog::directory().path()
Q3FileDialog::iconProvider()N/A
Q3FileDialog::isContentsPreviewEnabled()N/A
Q3FileDialog::isInfoPreviewEnabled()N/A
Q3FileDialog::previewMode()N/A
Q3FileDialog::rereadDir()N/A
Q3FileDialog::resortDir()N/A
Q3FileDialog::selectAll(bool)N/A
Q3FileDialog::setContentsPreview(QWidget *,Q3FilePreview *)N/A
Q3FileDialog::setContentsPreviewEnabled(bool)N/A
Q3FileDialog::setDir(constQString &)QFileDialog::setDirectory(constQString &)
Q3FileDialog::setFilters(const char **)Q3FileDialog::setFilters(constQStringList &)
Q3FileDialog::setIconProvider(Q3FileIconProvider *)N/A
Q3FileDialog::setInfoPreview(QWidget *,Q3FilePreview *)N/A
Q3FileDialog::setInfoPreviewEnabled(bool)N/A
Q3FileDialog::setPreviewMode(PreviewMode)N/A
Q3FileDialog::setSelectedFilter(constQString &)QFileDialog::selectFilter(constQString &)
Q3FileDialog::setSelectedFilter(int)See remark below
Q3FileDialog::setSelection(constQString &)QFileDialog::selectFile(constQString &)
Q3FileDialog::setShowHiddenFiles(bool)showHidden()
Q3FileDialog::setUrl(constQUrlOperator &)N/A
Q3FileDialog::showHiddenFiles()N/A
Q3FileDialog::url()QUrl::fromLocalFile(QFileDialog::directory())
Old signalsQt 4 equivalent
Q3FileDialog::fileHighlighted(constQString &)N/A
Q3FileDialog::fileSelected(constQString &)QFileDialog::filesSelected(constQStringList &)
Q3FileDialog::dirEntered(constQString &)N/A
Q3FileDialog::filterSelected(constQString &)N/A

Remarks:

  1. TheQ3FileDialog::addFilter(constQString &) function has no direct equivalent in the newQFileDialog. Use QFileDialog::setFilters() instead.

    For example, if you have code like

        fileDialog->addFilter(tr("JPEG files (*.jpg *.jpeg)"));

    you can rewrite it as

    QStringList filters= fileDialog->filters();    filters<< tr("JPEG files (*.jpg *.jpeg)");    fileDialog->setFilters(filters);
  2. TheQ3FileDialog::setSelectedFilter(int) overload has no direct equivalent in the newQFileDialog. Use QFileDialog::selectFilter(constQString &) instead.

    For example, if you have code like

        fileDialog->setSelectedFilter(3);

    you can rewrite it as

        fileDialog->selectFilter(fileDialog->filters().at(3));

There are no equivalent virtual functions to the twoQ3FileDialog::setSelectedFilter() virtual functions in theQFileDialog API. In addition, these functions have been renamed or removed, as described above.

QFocusData

TheQFocusData class is not available in Qt 4. Some of its functionality is available via theQWidget::nextInFocusChain() andQWidget::focusNextPrevChild() functions.

QFocusEvent

The setReason() function is no longer present in Qt 4. It is necessary to define the reason when constructing a focus event.

QFont

QFont::Script has been moved toQFontDatabase::WritingSystem.

QFrame

TheQFrame class has been made more lightweight in Qt 4, by reducing the number of properties and virtual functions. The reduction in the number of virtual functions is significant becauseQFrame is the base class of many Qt classes.

Here's an overview of the changes:

  • QFrame no longer has amargin property (which wasn't honored by Qt's layout managers anyway).
  • QFrame no longer has a frameChanged() function, reimplementQFrame::resizeEvent() instead.
  • QFrame used to have drawFrame(QPainter *) and drawContents(QPainter *) virtual functions. These are now gone. In Qt 4, the frame is drawn by theQFrame::paintEvent() function. If you want to change the wayQFrame paints itself, reimplement this function. To draw the contents of the frame, reimplementQFrame:paintEvent() and call the base class implementation of the function before you use thecontentsRect() function inherited fromQWidget, to retrieve the rectangle to paint on.

To help with porting, theQt3Support library contains aQ3Frame class that inheritsQFrame and provides a similar API to the oldQFrame class. If you derived fromQFrame in your application, you might want to useQ3Frame as a base class as a first step in the porting process, and later move on to the newQFrame class.

SeeVirtual Functions for a list ofQFrame virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QFtp

QFtp no longer inherits fromQNetworkProtocol. See thesection on QNetworkProtocol for details.

The oldQFtp class has been renamedQ3Ftp and moved to theQt3Support library.

QGLayoutIterator

TheQGLayoutIterator class no longer exists in Qt 4. This makes only a difference if you implemented custom layout managers (i.e.,QLayout subclasses).

The new approach is much simpler: It consists in reimplementingQLayout::itemAt() andQLayout::takeAt(). These functions operate on indexes, eliminating the need for a layout iterator class.

QGrid

TheQGrid class is now only available asQ3Grid in Qt 4. You can achieve the same result asQGrid by creating aQWidget with a grid layout:

For example, if you have code like

QGrid *grid = new QGrid(2, Qt::Horizontal);QPushButton *child1 = new QPushButton(grid);QPushButton *child2 = new QPushButton(grid);QPushButton *child3 = new QPushButton(grid);QPushButton *child4 = new QPushButton(grid);

you can rewrite it as

QWidget*grid=newQWidget;QPushButton*child1=newQPushButton(grid);QPushButton*child2=newQPushButton(grid);QPushButton*child3=newQPushButton(grid);QPushButton*child4=newQPushButton(grid);QVBoxLayout*layout=newQVBoxLayout;layout->addWidget(child1,0,0);layout->addWidget(child2,0,1);layout->addWidget(child3,1,0);layout->addWidget(child4,1,1);grid->setLayout(layout);

QGridLayout

SeeVirtual Functions for a list ofQGridLayout virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QGridView

TheQGridView class has been renamedQ3GridView and moved to theQt3Support library. In Qt 4, we recommend that you useQTableView orQAbstractItemView for presenting tabular data.

SeeModel/View Programming for an overview of the new item view classes.

QGroupBox

TheQGroupBox class has been redesigned in Qt 4. Many of the features of the oldQGroupBox class can be obtained by using theQ3GroupBox class from theQt3Support library.

The newQGroupBox is more lightweight. It doesn't attempt to duplicate functionality already provided byQGridLayout, and it does not inherit fromQFrame. As a result, the following members have been removed:

Naturally, thecolumns andorientation properties have also been removed.

If you rely on some of the missing functionality in your application, you can useQ3GroupBox instead ofQGroupBox as a help to porting.

SeeVirtual Functions for a list ofQGroupBox virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QHBox

TheQHBox class is now only available asQ3HBox in Qt 4. You can achieve the same result asQHBox by creating aQWidget with an horizontal layout:

For example, if you have code like

QHBox *hbox = new QHBox;QPushButton *child1 = new QPushButton(hbox);QPushButton *child2 = new QPushButton(hbox);

you can rewrite it as

QWidget*hbox=newQWidget;QPushButton*child1=newQPushButton;QPushButton*child2=newQPushButton;QHBoxLayout*layout=newQHBoxLayout;layout->addWidget(child1);layout->addWidget(child2);hbox->setLayout(layout);

Note that child widgets are not automatically placed into the widget's layout; you will need to manually add each widget to theQHBoxLayout.

QHeader

TheQHeader class has been renamedQ3Header and moved to theQt3Support library. In Qt 4, it is replaced by theQHeaderView class.

SeeModel/View Programming for an overview of the new item view classes.

QHGroupBox

TheQHGroupBox class has been renamedQ3HGroupBox and moved to theQt3Support library. Qt 4 does not provide a specific replacement class forQHGroupBox sinceQGroupBox is designed to be a generic container widget. As a result, you need to supply your own layout for any child widgets.

See#QGroupBox for more information about porting code that uses group boxes.

QHttp

QHttp no longer inherits fromQNetworkProtocol. See the See thesection on QNetworkProtocol for details.

The oldQHttp,QHttpHeader,QHttpRequestHeader, andQHttpResponseHeader classes have been renamedQ3Http,Q3HttpHeader,Q3HttpRequestHeader, andQ3HttpResponseHeader and have been moved to theQt3Support library.

QIconFactory

TheQIconFactory class is no longer part of Qt. It has been replaced by theQIconEngine class.

QIconSet

TheQIconSet class is no longer part of Qt. It has been replaced by theQIcon class.

QIconView

TheQIconView,QIconViewItem,QIconDrag, andQIconDragItem classes has been renamedQ3IconView,Q3IconViewItem,Q3IconDrag, andQ3IconDragItem and moved to theQt3Support library. New Qt applications should useQListWidget or its base classQListView instead, and callQListView::setViewMode(QListView::IconMode) to obtain an "icon view" look.

SeeModel/View Programming for an overview of the new item view classes.

QImageDrag

TheQImageDrag class has been renamedQ3ImageDrag and moved to theQt3Support library. In Qt 4, useQMimeData instead and call QMimeData::setImage() to set the image.

SeePorting to Qt 4 - Drag and Drop for a comparison between the drag and drop APIs in Qt 3 and Qt 4.

QImageIO

TheQImageIO class has been split into two classes:QImageReader andQImageWriter. The table below shows the correspondance between the two APIs:

Qt 3 functionQt 4 equivalents
QImageIO::description()QImageWriter::text()
QImageIO::fileName()QImageReader::fileName() andQImageWriter::fileName()
QImageIO::format()QImageReader::format() andQImageWriter::format()
QImageIO::gamma()QImageWriter::gamma()
QImageIO::image()Return value ofQImageReader::read()
QImageIO::inputFormats()QImageReader::supportedImageFormats()
QImageIO::ioDevice()QImageReader::device() andQImageWriter::device()
QImageIO::outputFormats()QImageWriter::supportedImageFormats()
QImageIO::parameters()N/A
QImageIO::quality()QImageWriter::quality()
QImageIO::read()QImageReader::read()
QImageIO::setDescription()QImageWriter::setText()
QImageIO::setFileName()QImageReader::setFileName() andQImageWriter::setFileName()
QImageIO::setFormat()QImageReader::setFormat() andQImageWriter::setFormat()
QImageIO::setGamma()QImageWriter::setGamma()
QImageIO::setIODevice()QImageReader::setDevice() andQImageWriter::setDevice()
QImageIO::setImage()Argument toQImageWriter::write()
QImageIO::setParameters()N/A
QImageIO::setQuality()QImageWriter::setQuality()
QImageIO::setStatus()N/A
QImageIO::status()QImageReader::error() andQImageWriter::error()
QImageIO::write()QImageWriter::write()

QIntCache<T>

QIntCache<T> has been moved toQt3Support. It has been replaced byQCache<int, T>.

For details, read thesection on QCache<T>, mentally substitutingint forQString.

QIntDict<T>

QIntDict<T> and QIntDictIterator<T> have been moved toQt3Support. They have been replaced by the more modernQHash<Key, T> andQMultiHash<Key, T> classes and their associated iterator classes.

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

For details, read thesection on QDict<T>, mentally substitutingint forQString.

QIODevice

TheQIODevice class's API has been simplified to make it easier to subclass and to make it work more smoothly with asynchronous devices such asQTcpSocket andQProcess.

The following virtual functions have changed name or signature:

Qt 3 functionComment
QIODevice::at() constRenamedQIODevice::pos().
QIODevice::at(Offset)RenamedQIODevice::seek().
QIODevice::open(int)The parameter is now of typeQIODevice::OpenMode.
QIODevice::readBlock(char *,Q_ULONG)QIODevice::read(char *, qint64)
QIODevice::writeBlock(const char *,Q_ULONG)QIODevice::write(const char *, qint64)

Note:QIODevice::open(QIODevice::OpenMode) is no longer pure virtual.

The following functions are no longer virtual or don't exist anymore:

QIODevice::getch()RenamedQIODevice::getChar() and implemented in terms ofQIODevice::readData().
QIODevice::putch(int)RenamedQIODevice::putChar() and implemented in terms ofQIODevice::writeData().
QIODevice::readAll()Implemented in terms ofQIODevice::readData().
QIODevice::readLine(char *,Q_ULONG)Implemented in terms ofQIODevice::readData()
QIODevice::ungetch(int)RenamedQIODevice::ungetChar() and simulated using an internal unget buffer.

TheIO_xxx flags have been revised, and the protected setFlags() function removed. Most of the flags have been eliminated because errors are best handled by implementing certain functions inQIODevice subclasses rather than through the base classes. The file access flags, such asIO_ReadOnly andIO_WriteOnly, have been moved to theQIODevice class to avoid polluting the global namespace. The table below shows the correspondence between the Qt 3IO_xxx flags and the Qt 4 API:

Qt 3 constantQt 4 equivalent
IO_DirectUse !QIODevice::isSequential() instead (notice thenot).
IO_SequentialUseQIODevice::isSequential() instead.
IO_CombinedN/A
IO_TypeMaskN/A
IO_RawQIODevice::Unbuffered
IO_AsyncN/A
IO_ReadOnlyQIODevice::ReadOnly
IO_WriteOnlyQIODevice::WriteOnly
IO_ReadWriteQIODevice::ReadWrite
IO_AppendQIODevice::Append
IO_TruncateQIODevice::Truncate
IO_TranslateQIODevice::Text
IO_ModeMaskN/A
IO_OpenUseQIODevice::isOpen() instead.
IO_StateMaskN/A
IO_OkN/A
IO_ReadErrorN/A
IO_WriteErrorN/A
IO_FatalErrorN/A
IO_ResourceErrorN/A
IO_OpenErrorN/A
IO_ConnectErrorN/A
IO_AbortErrorN/A
IO_TimeOutErrorN/A
IO_UnspecifiedErrorN/A

QIODeviceSource

TheQIODeviceSource 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 theTask Tracker on the Qt website and we will try to find a satisfactory substitute.

QLabel

QLabel doesn't enable word-wrap automatically anymore when rich text is used. You can enable it by callingQLabel::setWordWrap() or by setting thewordWrap property. The reason for this change is that the old behavior was confusing to many users.

Also,QLabel no longer offers anautoResize property. Instead, you can callQWidget::setFixedSize() on the label, withQLabel::sizeHint() as the argument, whenever you change the contents of theQLabel.

See alsoVirtual Functions for a list ofQLabel virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QLayout

In Qt 4, margins are always handled by layouts; there is no QLayout::setSupportsMargin() function anymore.

The deleteAllItems() function is now only available ifQT3_SUPPORT is defined. If you maintain aQList of layout items, you can useqDeleteAll() to remove all the items in one go.

In Qt 3, it was possible to change the resizing behavior for layouts in top-level widgets by adjusting the layout'sresizeMode property. In Qt 4, this property has been replaced by theQLayout::sizeConstraint property which provides more control over how the layout behaves when resized.

See also thesection on QLayoutIterator and thesection on QGLayoutIterator.

QLayoutIterator

TheQLayoutIterator class is obsoleted in Qt 4. It is available only ifQT3_SUPPORT is defined. It can be replaced by theQLayout::itemAt() andQLayout::takeAt() functions, which operate on indexes.

For example, if you have code like

    QLayoutIterator it = layout()->iterator();    QLayoutItem *child;    while ((child = it.current()) != 0) {        if (child->widget() == myWidget) {            it.takeCurrent();            return;        ++it;    }

you can rewrite it as

int i=0;QLayoutItem*child;while ((child= layout()->itemAt(i))!=0) {if (child->widget()== myWidget) {            layout()->takeAt(i);return;        }++i;    }

QLineEdit

SeeProperties for a list ofQLineEdit properties in Qt 3 that have changed in Qt 4.

The default value ofQLineEdit'sdragEnabled property wastrue in Qt 3. In Qt 4, the default value isfalse.

Note thatQLineEdit in Qt 4 is no longer a subclass ofQFrame. If you need to visually style a line edit with a frame, we recommend either using aQFrame as a container for aQLineEdit or customizing the line edit with astyle sheet.

QListBox

TheQListBox,QListBoxItem,QListBoxText, andQListBoxPixmap classes have been renamedQ3ListBox,Q3ListBoxItem,Q3ListBoxText, andQ3ListBoxPixmap and have been moved to theQt3Support library. New Qt applications should useQListWidget or its base classQListView instead.

SeeModel/View Programming for an overview of the new item view classes.

QListView

TheQListView,QListViewItem,QCheckListItem, andQListViewItemIterator classes have been renamedQ3ListView,Q3ListViewItem,Q3CheckListItem, andQ3ListViewItemIterator, and have been moved to theQt3Support library. New Qt applications should use one of the following four classes instead:QTreeView orQTreeWidget for tree-like structures;QListWidget or the newQListView class for one-dimensional lists.

SeeModel/View Programming for an overview of the new item view classes.

QLocalFs

TheQLocalFs class is no longer part of the public Qt API. It has been renamedQ3LocalFs and moved toQt3Support. UseQDir,QFileInfo, orQFile instead.

QMainWindow

TheQMainWindow class has been redesigned in Qt 4 to provide a more modern look and feel and more flexibility. The API has changed to reflect that. The oldQMainWindow class has been renamedQ3MainWindow and moved toQt3Support. See theQMainWindow class documentation for details.

QMemArray<T>

QMemArray<T> has been moved toQt3Support. It has been replaced by theQVector<T> class.

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

QMemArray::assign(const QMemArray<T> &)QVector::operator=()
QMemArray::assign(const T *, uint)See remark below
QMemArray::duplicate(const QMemArray &)QVector::operator=()
QMemArray::duplicate(const T *, uint)See remark below
QMemArray::setRawData(const T *, uint)N/A
QMemArray::resetRawData(const T *, uint)N/A
QMemArray::find(const T &, uint)QVector::indexOf(const T &, int)
QMemArray::contains(const T &)QVector::count(const T &)
QMemArray::sort()qSort()
QMemArray::bsearch(const T &d)qBinaryFind()
QMemArray::at(uint)QVector::operator[]()
QMemArray::operator const T *()QVector::constData()

Remarks:

  1. QMemArray::assign(const T *, uint) and QMemArray::duplicate(const T *, uint) can be replaced byQVector::resize() andqCopy().

    For example, if you have code like

        QMemArray<QSize> array;    ...    array.assign(data, size);

    you can rewrite it as

    QVector<QSize> vector;...    vector.resize(size);qCopy(data, data+ size, vector.begin());
  2. QMemArray is an explicitly shared class, whereasQVector is implicitly shared. SeeExplicit Sharing for more information.

QMenuBar

In Qt 3,QMenuBar inherited fromQFrame andQMenuData; in Qt 4, it is a direct subclass ofQWidget. Applications that provided customized menu bars will need to take advantage of the styling features described in theQt Style Sheets document.

It is not possible to add widgets to menu bars in Qt 4.

QMenuData

In Qt 4, theQMenu class provides a menu widget that can be used in all the places where menus are used in an application. UnlikeQMenuData,QMenu is designed around the concept of actions, provided by theQAction class, instead of the identifiers used in Qt 3.

In Qt 3, it was possible to insert widgets directly into menus by using a specificQMenuData::insertItem() overload. In Qt 4.2 and later, theQWidgetAction class can be used to wrap widgets for use in Qt 4's action-based APIs.

QMessageBox

TheQMessageBox::iconPixmap() function used to return a "constQPixmap *". In Qt 4, it returns aQPixmap.

QMimeSourceFactory

TheQMimeSourceFactory has been renamedQ3MimeSourceFactory and moved to theQt3Support library. New Qt applications should use Qt 4'sResource System instead.

QMovie

TheQMovie API has been revised in Qt 4 to make it more consistent with the other Qt classes (notablyQImageReader). The table below summarizes the changes.

Qt 3 functionQt 4 equivalent
QMovie::connectResize()Connect toQMovie::resized()
QMovie::connectStatus()Connect toQMovie::stateChanged()
QMovie::connectUpdate()Connect toQMovie::updated()
QMovie::disconnectResize()Disconnect fromQMovie::resized()
QMovie::disconnectStatus()Disconnect fromQMovie::stateChanged()
QMovie::disconnectUpdate()Disconnect fromQMovie::updated()
QMovie::finished()UseQMovie::state() instead
QMovie::frameImage()UseQMovie::currentImage() instead
QMovie::frameNumber()UseQMovie::currentFrameNumber() instead
QMovie::framePixmap()UseQMovie::currentPixmap() instead
QMovie::getValidRect()Use frameRect() instead
QMovie::isNull()UseQMovie::isValid() instead
QMovie::pause()UseQMovie::setPaused(true) instead
QMovie::paused()UseQMovie::state() instead
QMovie::pushData()N/A
QMovie::pushSpace()N/A
QMovie::restart()UseQMovie::jumpToFrame(0) instead
QMovie::running()UseQMovie::state() instead
QMovie::step()UseQMovie::jumpToFrame() andQMovie::setPaused() instead
QMovie::step()UseQMovie::jumpToNextFrame() instead
QMovie::steps()UseQMovie::currentFrameNumber() andQMovie::frameCount() instead
QMovie::unpause()UseQMovie::setPaused(false) instead

QMultiLineEdit

TheQMultiLineEdit class in Qt 3 was a convenienceQTextEdit subclass that provided an interface compatible with Qt 2'sQMultiLineEdit class. In Qt 4, it is calledQ3MultiLineEdit, it inheritsQ3TextEdit, and it is part ofQt3Support. UseQTextEdit in new code.

QNetworkProtocol

TheQNetworkProtocol, QNetworkProtocolFactoryBase, QNetworkProtocolFactory<T>, and QNetworkOperation classes are no longer part of the public Qt API. They have been renamedQ3NetworkProtocol, Q3NetworkProtocolFactoryBase, Q3NetworkProtocolFactory<T>, andQ3NetworkOperation and have been moved to theQt3Support library.

In Qt 4 applications, you can use classes likeQFtp andQNetworkAccessManager directly to perform file-related actions on a remote host.

QObject

QObject::children() now returns aQObjectList instead of a pointer to aQObjectList. See also the comments onQObjectList below.

UseQObject::findChildren() instead of QObject::queryList(). For example:

QList<QWidget*> myWidgets= myParent->findChildren<QWidget*>();

QObject::killTimers() has been removed because it was unsafe to use in subclass. (A subclass normally doesn't know whether the base class uses timers or not.)

TheQObject::name property has been renamedQObject::objectName.

QObject::objectTrees() has been removed. If you are primarly interested in widgets, useQApplication::allWidgets() orQApplication::topLevelWidgets().

QObjectDictionary

TheQObjectDictionary class is a synonym for QAsciiDict<QMetaObject>. See thesection on QAsciiDict<T>.

QObjectList

In Qt 3, theQObjectList class was a typedef for QPtrList<QObject>. In Qt 4, it is a typedef forQList<QObject *>. See thesection on QPtrList<T>.

QPaintDevice

To reimplement painter backends one previously needed to reimplement the virtual function QPaintDevice::cmd(). This function is taken out and should is replaced with the functionQPaintDevice::paintEngine() and the abstract classQPaintEngine.QPaintEngine provides virtual functions for all drawing operations that can be performed on a painter backend.

bitBlt() and copyBlt() are now only compatibility functions. UseQPainter::drawPixmap() instead.

QPaintDeviceMetrics

All functions that used to be provided by theQPaintDeviceMetrics class have now been moved toQPaintDevice.

For example, if you have code like

    QPaintDeviceMetrics metrics(widget);    int deviceDepth = metrics.depth();

you can rewrite it as

int deviceDepth= widget->depth();

For compatibility, the oldQPaintDeviceMetrics class has been renamedQ3PaintDeviceMetrics and moved toQt3Support.

QPainter

TheQPainter class has undergone some changes in Qt 4 because of the way rectangles are drawn. In Qt 4, the result of drawing aQRect with a pen width of 1 pixel is 1 pixel wider and 1 pixel taller than in Qt 3.

For compatibility, we provide aQ3Painter class inQt3Support that provides the old semantics. See theQ3Painter documentation for details and for the reasons why we had to make this change.

TheQPainter::CoordinateMode enum has been removed in Qt 4. All clipping operations are now defined using logical coordinates and are subject to transformation operations.

TheQPainter::RasterOP enum has been replaced withQPainter::CompositionMode.

QPicture

In Qt 3, aQPicture could be saved in the SVG file format. In Qt 4, the SVG support is provided by theQtSvg module, which includes classes fordisplaying the contents of SVG files.

If you would like to generate SVG files, you can use theQ3Picture compatibility class or theQSvgGenerator class introduced in Qt 4.3.

QPixmap

The mask() function has been changed to return a reference to aQBitmap rather than a pointer. As a result, it is no longer possible simply to test for a null pointer when determining whether a pixmap has a mask. Instead, you need to explicitly test whether the mask bitmap is null or not.

For example, if you have code like

    if (pixmap.mask())        widget->setMask(*pixmap.mask());

you can rewrite it as

if (!pixmap.mask().isNull())        widget->setMask(pixmap.mask());

TheQPixmap::setOptimization() andQPixmap::setDefaultOptimization() mechanism is no longer available in Qt 4.

QPointArray

TheQPointArray class has been renamedQPolygon in Qt 4 and has undergone significant changes. In Qt 3,QPointArray inherited from QMemArray<QPoint>. In Qt 4,QPolygon inherits fromQVector<QPoint>. Everything mentioned in thesection on QMemArray<T> apply forQPointArray as well.

TheQt3Support library contains aQ3PointArray class that inherits fromQPolygon and provides a few functions that existed inQPointArray but no longer exist inQPolygon. These functions includeQ3PointArray::makeArc(),Q3PointArray::makeEllipse(), andQ3PointArray::cubicBezier(). In Qt 4, we recommend that you useQPainterPath for representing arcs, ellipses, and Bezier curves, rather thanQPolygon.

TheQPolygon::setPoints() andQPolygon::putPoints() functions returnvoid in Qt 4. The corresponding Qt 3 functions returned abool indicating whether the array was successfully resized or not. This can now be checked by checkingQPolygon::size() after the call.

QPopupMenu

For most purposes,QPopupMenu has been replaced byQMenu in Qt 4. For compatibility with older applications,Q3PopupMenu provides the old API and features that are specific to pop-up menus. Note that, when usingQ3PopupMenu, the menu's actions must beQ3Actions.

In Qt 3, it was common practice to add entries to pop-up menus using the insertItem() function, maintaining identifiers for future use; for example, to dynamically change menu items. In Qt 4, menu entries are completely represented by actions for consistency with other user interface components, such as toolbar buttons. Create new menus with theQMenu class, and use the overloadedQMenu::addAction() functions to insert new entries. If you need to manage a set of actions created for a particular menu, we suggest that you construct aQActionGroup and add them to that.

TheMain Window Examples provided show how to use Qt's action system to construct menus, toolbars, and other common user interface elements.

QPrinter

TheQPrinter class now expects printing to be set up from aQPrintDialog.

QProcess

TheQProcess class has undergone major improvements in Qt 4. It now inheritsQIODevice, which makes it possible to combineQProcess with aQTextStream or aQDataStream.

The oldQProcess class has been renamedQ3Process and moved to theQt3Support library.

QProgressBar

TheQProgressBar API has been significantly improved in Qt 4. The oldQProgressBar API is available asQ3ProgressBar in theQt3Support library.

QProgressDialog

TheQProgressDialog API has been significantly improved in Qt 4. The oldQProgressDialog API is available asQ3ProgressDialog in theQt3Support library.

SeeProperties for a list ofQProgressDialog properties in Qt 3 that have changed in Qt 4.

QPtrCollection<T>

TheQPtrCollection<T> abstract base class has been renamedQ3PtrCollection<T> moved to theQt3Support library. There is no direct equivalent in Qt 4.

SeeContainer Classes for a list of Qt 4 containers.

QPtrDict<T>

QPtrDict<T> andQPtrDictIterator<T> have been renamedQ3PtrDict<T> andQ3PtrDictIterator<T> and have been moved to theQt3Support library. They have been replaced by the more modernQHash<Key, T> andQMultiHash<Key, T> classes and their associated iterator classes.

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

(You can naturally use other types thanvoid * for the key type, e.g.QWidget *.)

To portQ3PtrDict<T> to Qt 4, read thesection on QDict<T>, mentally substitutingvoid * forQString.

QPtrList<T>

QPtrList<T>, QPtrListIterator<T>, and QPtrListStdIterator<T> have been moved to theQt3Support library. They have been replaced by the more modernQList andQLinkedList classes and their associated iterator classes.

When porting to Qt 4, you have the choice of usingQList<T> orQLinkedList<T> as alternatives to QValueList<T>.QList<T> has an index-based API and provides very fast random access (QList::operator[]), whereasQLinkedList<T> has an iterator-based API.

The following table summarizes the API differences between QPtrList<T> andQList<T *>:

QPtrList functionQList equivalent
QPtrList::contains(const T *)QList::count(T *)
QPtrList::containsRef(const T *)QList::count(T *)
QPtrList::find(const T *)See remark below
QPtrList::findRef(const T *)See remark below
QPtrList::getFirst()QList::first()
QPtrList::getLast()QList::last()
QPtrList::inSort(const T *)N/A
QPtrList::remove(const T *)QList::removeAll(T *)
QPtrList::remove(uint)QList::removeAt(int)
QPtrList::removeNode(QLNode *)N/A
QPtrList::removeRef(const T *)QList::removeAll(T *)
QPtrList::sort()See remark below
QPtrList::takeNode(QLNode *)N/A
QPtrList::toVector(QGVector *)See remark below

Remarks:

  1. QPtrList::toVector(QGVector *) can be replaced byQVector::resize() andqCopy().

    For example, if you have code like

        QPtrList<QWidget> list;    ...    QPtrVector<QWidget> vector;    list.toVector(&vector);

    you can rewrite it as

    QList<QWidget*> list;...QVector<QWidget*> vector;    vector.resize(list.size());qCopy(list.begin(), list.end(), vector.begin());
  2. QPtrList::sort() relied on the virtual compareItems() to sort items. In Qt 4, you can useqSort() instead and pass your "compare item" function as an argument.
  3. QPtrList::find(const T *) returns an iterator, whereasQList::indexOf(T *) returns an index. To convert an index into an iterator, add the index toQList::begin().
  4. QPtrList::removeFirst() and QPtrList::removeLast() return abool that indicates whether the element was removed or not. The correspondingQList functions returnvoid. You can achieve the same result by callingQList::isEmpty() before attempting to remove an item.

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

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

QPtrList idiomQList idiom
list.replace(index, value);
delete list[index];list[index]= value;
list.removeFirst();
delete list.takeFirst();
list.removeLast();
delete list.takeLast();
list.remove(index);
delete list.takeAt(index);
list.remove(value);
int i= list.indexOf(value);if (i!=-1)delete list.takeAt(i);
list.remove();

(removes the current item)

QMutableListIterator<T*> i;...delete i.value();i.remove();
list.clear();

(also called from QPtrList's destructor)

while (!list.isEmpty())delete list.takeFirst();

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

qDeleteAll(list);list.clear();

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

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

QPtrList had the concept of a "current item", which could be used for traversing the list without using an iterator. When porting to Qt 4, you can use the Java-styleQListIterator<T *> (orQMutableListIterator<T *>) class instead. The following table summarizes the API differences:

QPtrList functionQListIterator equivalent
QPtrList::at()N/A
QPtrList::current()QMutableListIterator::value()
QPtrList::currentNode()N/A
QPtrList::findNext(const T *)QListIterator::findNext(const T *)
QPtrList::findNextRef(const T *)QListIterator::findNext(const T *)
QPtrList::first()QPtrList::toFront()
QPtrList::last()QPtrList::toBack()
QPtrList::next()QPtrList::next()
QPtrList::prev()QPtrList::previous()
QPtrList::remove()QMutableListIterator::remove()
QPtrList::take()QMutableListIterator::remove()

Be aware thatQListIterator has a different way of iterating than QPtrList. A typical loop with QPtrList looks like this:

QPtrList<QWidget> list;...while (list.current()!=0) {    do_something(list.current());    list.next();}

Here's the equivalentQListIterator loop:

QList<QWidget*> list;...QListIterator<QWidget*> i(list);while (i.hasNext())    do_something(i.next());

Finally, QPtrListIterator<T> must also be ported. There are no fewer than four iterator classes that can be used as a replacement:QList::const_iterator,QList::iterator,QListIterator, andQMutableListIterator. The most straightforward class to use when porting isQMutableListIterator<T *> (if you modify the list through the iterator) orQListIterator<T *> (if you don't). The following table summarizes the API differences:

QPtrListIterator functionQt 4 equivalent
QPtrListIterator::atFirst()!QListIterator::hasPrevious() (notice the!)
QPtrListIterator::atLast()!QListIterator::hasNext() (notice the!)
QPtrListIterator::count()QList::count() orQList::size()
QPtrListIterator::current()QMutableListIterator::value()
QPtrListIterator::isEmpty()QList::isEmpty()
QPtrListIterator::toFirst()QListIterator::toFront()
QPtrListIterator::toLast()QListIterator::toBack()
QPtrListIterator::operator()QMutableListIterator::value()
QPtrListIterator::operator*()QMutableListIterator::value()

Again, be aware thatQListIterator has a different way of iterating than QPtrList. A typical loop with QPtrList looks like this:

QPtrList<QWidget> list;...QPtrListIterator<QWidget> i;while (i.current()!=0) {    do_something(i.current());    i.next();}

Here's the equivalentQListIterator loop:

QList<QWidget*> list;...QListIterator<QWidget*> i(list);while (i.hasNext())    do_something(i.next());

Finally, QPtrListStdIterator<T> must also be ported. This is easy, becauseQList also provides STL-style iterators (QList::iterator andQList::const_iterator).

QPtrQueue<T>

QPtrQueue has been moved to theQt3Support library. It has been replaced by the more modernQQueue class.

The following table summarizes the differences between QPtrQueue<T> andQQueue<T *>:

QPtrQueue functionQQueue equivalent
QPtrQueue::autoDelete()See discussion below
QPtrQueue::count()QQueue::count() orQQueue::size() (equivalent)
QPtrQueue::current()QQueue::head()
QPtrQueue::remove()QQueue::dequeue()
QPtrQueue::setAutoDelete()See discussion below

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

QPtrQueue idiomQQueue idiom
queue.dequeue();
delete queue.dequeue();
queue.remove();
delete queue.dequeue();
queue.clear();

(also called from QPtrQueue's destructor)

while (!queue.isEmpty())delete queue.dequeue();

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

qDeleteAll(queue);queue.clear();

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

QPtrStack<T>

QPtrStack has been moved to theQt3Support library. It has been replaced by the more modernQStack class.

The following table summarizes the differences between QPtrStack<T> andQStack<T *>:

QPtrStack functionQStack equivalent
QPtrStack::autoDelete()See discussion below
QPtrStack::count()QStack::count() orQStack::size() (equivalent)
QPtrStack::current()QStack::top()
QPtrStack::remove()QStack::pop()
QPtrStack::setAutoDelete()See discussion below

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

QPtrStack idiomQStack idiom
stack.pop();
delete stack.pop();
stack.remove();
delete stack.pop();
stack.clear();

(also called from QPtrStack's destructor)

while (!stack.isEmpty())delete stack.pop();

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

qDeleteAll(stack);stack.clear();

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

QPtrVector<T>

QPtrVector<T> has been moved toQt3Support. It has been replaced by the more modernQVector class.

When porting to Qt 4, you can useQVector<T *> as an alternative to QPtrVector<T>. The APIs of QPtrVector<T> andQVector<T *> are somewhat similar. The main issue is that QPtrVector supports auto-delete whereasQVector doesn't.

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

QPtrVector functionQVector equivalent
QPtrVector::autoDelete()See discussion below
QPtrVector::bsearch(const T *)qBinaryFind()
QPtrVector::contains(const T *)QVector::count(T *)
QPtrVector::containsRef(const T *)QVector::count(T *)
QPtrVector::count()See remark below
QPtrVector::insert(uint, T *)See remark below
QPtrVector::isNull()N/A
QPtrVector::remove(uint)See remark below
QPtrVector::setAutoDelete()See discussion below
QPtrVector::sort()qSort()
QPtrVector::take(uint)See remark below
QPtrVector::toList(QGList *)QList::QList(constQVector &)

Remarks:

  1. QPtrVector::insert(uint, T *) sets an item to store a certain pointer value. This isnot the same asQVector::insert(int, T *), which creates space for the item by moving following items by one position. Usevect[i] = ptr to set aQVector item to a particular value.
  2. QPtrVector::remove(uint) sets an item to be 0. This isnot the same as QVector::removeAt(int), which entirely erases the item, reducing the size of the vector. Usevect[i] = 0 to set aQVector item to 0.
  3. Likewise, QPtrVector::take(uint) sets an item to be 0 and returns the previous value of the item. Again, this is easy to achieve using QVector::operator[]().
  4. QPtrVector::count() returns the number of non-null items in the vector, whereasQVector::count() (likeQVector::size()) returns the number of items (null or non-null) in the vector. Fortunately, it's not too hard to simulate QPtrVector::count().

    For example, if you have code like

        int numValidItems = vect.count();

    you can rewrite it as

    int numValidItems= vect.size()- vect.count(0);

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

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

QPtrVector idiomQVector idiom
vect.insert(i, ptr);
delete vect[i];vect[i]= ptr;
vect.remove(i);
delete vect[i];vect[i]=0;
T*ptr= vect.take(i);
T*ptr= vect[i];vect[i]=0;
vect.resize(n)
while (n> vect.size())    vect.append(0);while (n< vect.size() {    T*ptr= vect.last();    vect.remove(vect.size()-1);delete ptr;}
vect.clear();

(also called from QPtrVector's destructor)

for (int i=0; i< vect.size();++i)    T*ptr= vect[i];    vect[i]=0;delete ptr;}

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

qDeleteAll(vect);vect.clear();

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

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

QPushButton

SeeProperties for a list ofQPushButton properties in Qt 3 that have changed in Qt 4.

QRangeControl

In Qt 3, various "range control" widgets (QDial,QScrollBar,QSlider, and QSpin) inherited from bothQWidget andQRangeControl.

In Qt 4,QRangeControl has been replaced with the newQAbstractSlider andQAbstractSpinBox classes, which inherit fromQWidget and provides similar functionality. Apart from eliminating unnecessary multiple inheritance, the new design allowsQAbstractSlider to provide signals, slots, and properties.

The oldQRangeControl class has been renamedQ3RangeControl and moved to theQt3Support library, together with the (undocumented)QSpinWidget class.

If you useQRangeControl as a base class in your application, you can switch to useQAbstractSlider orQAbstractSpinBox instead.

For example, if you have code like

    class VolumeControl : public QWidget, public QRangeControl    {        ...    protected:        void valueChange() {            update();            emit valueChanged(value());        }        void rangeChange() {            update();        }        void stepChange() {            update();        }    };

you can rewrite it as

class VolumeControl :publicQAbstractSlider    {...protected:void sliderChange(SliderChange change) {            update();if (change== SliderValueChange)emit valueChanged(value());        }    };

QRegExp

The search() and searchRev() functions have been renamed to indexIn() and lastIndexIn() respectively.

QRegion

The following changes have been made toQRegion in Qt 4:

  • There is no longer any difference between anull region and anempty region. Use isEmpty() in most places where you would have used a nullQRegion.
  • QRegion::rects() used to return a QMemArray<QRect>. It now returns aQVector<QRect>.

QScrollBar

SeeProperties for a list ofQScrollBar properties in Qt 3 that have changed in Qt 4.

QScrollView

TheQScrollView class has been renamedQ3ScrollView and moved to theQt3Support library. It has been replaced by theQAbstractScrollArea andQScrollArea classes.

Note that Qt 4 in general uses theQScrollArea::widget() function where Qt 3 used QScrollView::viewport(). The rationale for this is that it is no longer possible to draw directly on a scroll area. TheQScrollArea::widget() function returns the widget set on the scroll area.

QScrollView was designed to work around the 16-bit limitation on widget coordinates found on most window systems. In Qt 4, this is done transparently forall widgets, so there is no longer a need for such functionality inQScrollView. For that reason, the newQAbstractScrollArea andQScrollArea classes are much more lightweight, and concentrate on handling scroll bars.

QServerSocket

TheQServerSocket class has been renamedQ3ServerSocket and moved to theQt3Support library. In Qt 4, it has been replaced byQTcpServer.

WithQ3ServerSocket, connections are accepted by reimplementing a virtual function (Q3ServerSocket::newConnection()). WithQTcpServer, on the other hand, you don't need to subclass. Instead, simply connect to theQTcpServer::newConnection() signal.

QSettings

TheQSettings class has been rewritten to be more robust and to respect existing standards (e.g., the INI file format). The API has also been extensively revised. The old API is still provided when Qt 3 support is enabled.

Since the format and location of settings have changed between Qt 3 and Qt 4, the Qt 4 version of your application won't recognize settings written using Qt 3.

QShared

TheQShared class has been obsoleted by the more powerfulQSharedData andQSharedDataPointer as a means of creating custom implicitly shared classes. It has been renamedQ3Shared and moved to theQt3Support library.

An easy way of porting to Qt 4 is to include this class into your project and to use it instead ofQShared:

struct Shared{    Shared() : count(1) {}void ref() {++count; }    bool deref() {return!--count; }uint count;};

If possible, we recommend that you useQSharedData andQSharedDataPointer instead. They provide thread-safe reference counting and handle all the reference counting behind the scenes, eliminating the risks of forgetting to increment or decrement the reference count.

QSignal

TheQSignal class has been renamed toQ3Signal and moved to theQt3Support library. The preferred approach is to create your ownQObject subclass with a signal that has the desired signature. Alternatively, you can callQMetaObject::invokeMethod() if you want to invoke a slot.

QSimpleRichText

QSimpleRichText has been obsoleted byQTextDocument. It has been renamedQ3SimpleRichText and moved to theQt3Support library.

Previously, you would do the following withQ3SimpleRichText:

// Declare the objectQSimpleRichText richText(text, font);// Set the width of the paragraph to wrichText.setWidth(w);// Or set a reasonable default sizerichText.adjustSize();// Query for its used sizeint width= richText.widthUsed();int height= richText.height();// DrawrichText.draw(painter, x, y, clipRect, colorGroup);

However, withQTextDocument, you use the following code instead:

// Declare the objectQTextDocument doc;// If text is rich text, use setHtml()doc.setHtml(text);// Otherwise, use setPlainText()doc.setPlainText(text);// Set the width of the paragraph of text to wdoc.setTextWidth(w);// Query for the used sizeint width= doc.idealWidth();int height= doc.size().height();// Drawpainter.translate(x, y);doc.drawContents(painter, clipRect);// If you have a palette/colorgroup you can draw using lower-level functions:QAbstractTextDocumentLayout::PaintContext context;context.palette= myPalette;doc.documentLayout()->draw(painter, context);

SeeRich Text Processing for an overview of the Qt 4 rich text classes.

QSlider

The QSlider::sliderStart() and QSlider::sliderRect() functions have been removed.

The slider's rect can now be retrieved using the code snippet below:

QSlider*slider;slider->style()->subControlRect(CC_Slider, sliderOption, SC_SliderHandle, slider);

In addition, the direction of a verticalQSlider has changed, i.e. the bottom is now the minimum, and the top the maximum. You can use theQAbstractSlider::invertedAppearance property to control this behavior.

SeeProperties for a list ofQSlider properties in Qt 3 that have changed in Qt 4.

QSocket

TheQSocket class has been renamedQ3Socket and moved to theQt3Support library. In Qt 4, it has been replaced by theQTcpSocket class, which inherits most of its functionality fromQAbstractSocket.

QSocketDevice

TheQSocketDevice class has been renamedQ3SocketDevice and moved to theQt3Support library. In Qt 4, there is no direct equivalent toQ3SocketDevice:

  • If you useQ3SocketDevice in a thread to perform blocking network I/O (a technique encouraged by theQt Quarterly articleUnblocking Networking), you can now useQTcpSocket,QFtp, orQNetworkAccessManager, which can be used from non-GUI threads.
  • If you useQ3SocketDevice for UDP, you can now useQUdpSocket instead.
  • If you useQ3SocketDevice for other uses, Qt 4 offers no alternative right now. However, there is aQAbstractSocketEngine internal class that offers a low-level socket API similar toQ3SocketDevice. Should the need for such functionality arise in Qt 4 applications, we will consider making this class public in a future release.

QSortedList

TheQSortedList<T> class has been deprecated since Qt 3.0. In Qt 4, it has been moved to theQt3Support library.

In new code, we recommend that you useQList<T> instead and useqSort() to sort the items.

QSplitter

The function setResizeMode() has been moved intoQt3Support. Set the stretch factor in the widget's size policy to get equivalent functionality.

The obsolete function drawSplitter() has been removed. UseQStyle::drawPrimitive() to acheive similar functionality.

QSpinBox

SeeProperties for a list ofQSpinBox properties in Qt 3 that have changed in Qt 4.

QSqlCursor

TheQSqlCursor class has been renamedQ3SqlCursor and moved to theQt3Support library. In Qt 4, you can useQSqlQuery,QSqlQueryModel, orQSqlTableModel, depending on whether you want a low-level or a high-level interface for accessing databases.

SeeQtSql Module for an overview of the new SQL classes.

QSqlDatabase

QSqlDatabase is now a smart pointer that is passed around by value. Simply replace allQSqlDatabase pointers byQSqlDatabase objects.

QSqlEditorFactory

TheQSqlEditorFactory class has been renamedQ3SqlEditorFactory and moved toQt3Support.

SeeQtSql Module for an overview of the new SQL classes.

QSqlError

The enumType was renamed toErrorType, The values were renamed as well:

  • None - use NoError instead
  • Connection - use ConnectionError instead
  • Statement - use StatementError instead
  • Transaction - use TransactionError instead
  • Unknown - use UnknownError instead

QSqlFieldInfo

TheQSqlFieldInfo class has been moved toQt3Support. Its functionality is now provided by theQSqlField class.

SeeQtSql Module for an overview of the new SQL classes.

QSqlForm

TheQSqlForm class has been renamedQ3SqlForm and moved to theQt3Support library.

SeeQtSql Module for an overview of the new SQL classes.

QSqlPropertyMap

TheQSqlPropertyMap class has been renamedQ3SqlPropertyMap moved to theQt3Support library.

SeeQtSql Module for an overview of the new SQL classes.

QSqlQuery

QSqlQuery::prev() was renamed toQSqlQuery::previous().QSqlQuery::prev() remains, but it just calls previous().QSqlQuery no longer has any virtual methods, i.e., exec(), value(), seek(), next(), prev(), first(), last(), and the destructor are no longer virtual.

QSqlRecord

QSqlRecord behaves like a vector now,QSqlRecord::insert() will actually insert a new field instead of replacing the existing one.

QSqlRecordInfo

TheQSqlRecordInfo class has been moved toQt3Support. Its functionality is now provided by theQSqlRecord class.

SeeQtSql Module for an overview of the new SQL classes.

QSqlSelectCursor

TheQSqlSelectCursor class has been renamedQ3SqlSelectCursor and moved to theQt3Support library.

SeeQtSql Module for an overview of the new SQL classes.

QStoredDrag

TheQStoredDrag class has been renamedQ3StoredDrag and moved to theQt3Support library. In Qt 4, useQMimeData instead and callQMimeData::setData() to set the data.

SeePorting to Qt 4 - Drag and Drop for a comparison between the drag and drop APIs in Qt 3 and Qt 4.

QStr(I)List

The QStrList and QStrIList convenience classes have been deprecated since Qt 2.0. In Qt 4, they have been moved to theQt3Support library. If you used any of these, we recommend that you useQStringList orQList<QByteArray> instead.

QStr(I)Vec

The QStrVec and QStrIVec convenience classes have been deprecated since Qt 2.0. In Qt 4, they have been moved toQt3Support. If you used any of these, we recommend that you useQStringList orQList<QByteArray> instead.

QString

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

  1. TheQString::QString(QChar) constructor performed implicit conversion in Qt 3. Now, you will need a cast to convert aQChar to aQString.
  2. TheQString::QString(constQByteArray &) constructor used to stop at the first '\0' it encountered, for compatibility with Qt 1. This quirk has now been fixed; in Qt 4, the resultingQString always has the same length as theQByteArray that was passed to the constructor.
  3. TheQString::null static constant has been deprecated in Qt 4. For compatibility, Qt 4 provides aQString::null symbol that behaves more or less the same as the old constant. The new idiom is to write QString() instead ofQString::null, or to call clear().

    For example, if you have code like

            str1 = QString::null;        if (str2 == QString::null)            do_something(QString::null);

    you can rewrite it as

            str1.clear();if (str2.isNull())            do_something(QString());

    In new code, we recommend that you don't rely on the distinction between a null string and a (non-null) empty string. SeeDistinction Between Null and Empty Strings for details.

  4. QString::latin1() andQString::ascii() have been replaced withQString::toLatin1() andQString::toAscii(), which return aQByteArray instead of a (non-reentrant)const char *. For consistency,QString::utf8() andQString::local8Bit(), which already returned aQByteArray (actually aQCString), have been renamedQString::toUtf8() andQString::toLocal8Bit().

    To obtain aconst char * pointer to ASCII or Latin-1 data, useQString::toAscii() orQString::toLatin1() to obtain aQByteArray containing the data, then callQByteArray::constData() to access the character data directly. Note that the pointer returned by this function is only valid for the lifetime of the byte array; you should avoid taking a pointer to the data contained in temporary objects.

    QString greeting="Hello";constchar*badData= greeting.toAscii().constData();// data is invalidQByteArray asciiData= greeting.toAscii();constchar*goodData= asciiData.constData();

    In the above example, thegoodData pointer is valid for the lifetime of theasciiData byte array. If you need to keep a copy of the data in a non-Qt data structure, use standard C memory allocation and string copying functions to do sobefore destroying the byte array.

  5. QString::at() returned a non-const reference, whereas the newQString::at() returns a const value. Code like
    str.at(0)='X';

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

    str[0]='X';
  6. TheQString::contains(x) function (wherex is a character or a string) has been renamedQString::count(x). In addition, there now exists a set ofQString::contains() functions 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 string or only care about whether the string contains that character or not.
  7. Many functions inQString had abool parameter that specified case sensitivity. In Qt 4, in the interest of code readability and maintainability, thebool parameters have been replaced by theQt::CaseSensitivity enum, which can take the valuesQt::CaseSensitive andQt::CaseInsensitive.

    For example, if you have code like

            if (url.startsWith("http:", false))            ...

    you can rewrite it as

    if (url.startsWith("http:",Qt::CaseInsensitive))...
  8. The QString::setExpand(uint,QChar) function, which already was obsolete in Qt 3, is no longer available. Use QString::operator[] instead.

    For example, if you have code like

            str.setExpand(32, '$');

    you can rewrite it as

            str[32]='$';
  9. TheQT_NO_ASCII_CAST andQT_NO_CAST_ASCII macros have been renamedQT_NO_CAST_TO_ASCII andQT_NO_CAST_FROM_ASCII, respectively.
  10. TheQString::data() used to return the same asQString::ascii(). It now returns a pointer to the Unicode data stored in theQString object. CallQString::ascii() if you want the old behavior.
  11. QString::arg() now converts two-digit place markers, allowing up to 99 place markers to be used in any given string.
  12. Comparisons between QStrings andNULL in order to determine whether strings are empty are no longer allowed. UseisEmpty() instead.

QStringList

QStringList now inherits fromQList<QString> and can no longer be converted to a QValueList<QString>. Since QValueList inheritsQList a cast will work as expected.

This change implies some API incompatibilities forQStringList. For example, at() returns the string, not an iterator. See thesection on QValueList for details.

The staticQStringList::split() function for splitting strings into lists of smaller strings has been replaced byQString::split(), which returns aQStringList.

QStyle

TheQStyle API has been overhauled and improved. Most of the information on why this change was done is described inthe QStyle overview.

SinceQStyle is mostly used internally by Qt's widgets and styles and since it is not essential to the good functioning of an application, there is no compatibility path. This means that we have changed many enums and functions and the qt3to4 porting tool will not change much in your qstyle code. To ease the pain, we list some of the major changes here.

QStyleOption has taken on a more central role and is no longer an optional argument, please see theQStyleOption documentation for more information.

The QStyle::StyleFlags have been renamed QStyle::StateFlags and are now prefixed State_ instead of Style_, in addition the Style_ButtonDefault flag has moved toQStyleOptionButton.

TheQStyle::PrimitiveElement enumeration has undergone extensive change. Some of the enums were moved toQStyle::ControlElement, some were removed and all were renamed. This renaming is not done by the qt3to4 porting tool, so you must do it yourself. The table below shows how things look now.

Old nameNew nameRemark
PE_ButtonCommandQStyle::PE_PanelButtonCommand
PE_ButtonDefaultQStyle::PE_FrameDefaultButton
PE_ButtonBevelQStyle::PE_PanelButtonBevel
PE_ButtonToolQStyle::PE_PanelButtonTool
PE_ButtonDropDownQStyle::PE_IndicatorButtonDropDown
PE_FocusRectQStyle::PE_FrameFocusRect
PE_ArrowUpQStyle::PE_IndicatorArrowUp
PE_ArrowDownQStyle::PE_IndicatorArrowDown
PE_ArrowRightQStyle::PE_IndicatorArrowRight
PE_ArrowLeftQStyle::PE_IndicatorArrowLeft
PE_SpinBoxUpQStyle::PE_IndicatorSpinUp
PE_SpinBoxDownQStyle::PE_IndicatorSpinDown
PE_SpinBoxPlusQStyle::PE_IndicatorSpinPlus
PE_SpinBoxMinusQStyle::PE_IndicatorSpinMinus
PE_SpinBoxSliderQStyle::CE_SpinBoxSliderusesQStyle::drawControl()
PE_IndicatorQStyle::PE_IndicatorCheckBox
PE_IndicatorMaskN/AuseQStyle::styleHint() to retrieve mask
PE_ExclusiveIndicatorQStyle::PE_IndicatorRadioButton
PE_ExclusiveIndicatorMaskN/AuseQStyle::styleHint() to retrieve mask
PE_DockWindowHandleQStyle::PE_IndicatorToolBarHandle
PE_DockWindowSeparatorQStyle::PE_Q3DockWindowSeparator
PE_DockWindowResizeHandleQStyle::PE_IndicatorDockWindowResizeHandle
PE_DockWindowTitleQStyle::CE_DockWindowTitleusesQStyle::drawControl()
PE_SplitterQStyle::CE_SplitterusesQStyle::drawControl()
PE_PanelQStyle::PE_Frame
PE_PanelMenuQStyle::PE_FrameMenu
PE_PanelMenuBarQStyle::PE_PanelMenuBar
PE_PanelDockWindowQStyle::PE_FrameDockWindow
PE_TabBarBaseQStyle::PE_FrameTabBarBase
PE_HeaderSectionQStyle::CE_HeaderSectionusesQStyle::drawControl()
PE_HeaderArrowQStyle::PE_IndicatorHeaderArrow
PE_StatusBarSectionQStyle::PE_FrameStatusBar
PE_SeparatorQStyle::PE_Q3Separator
PE_SizeGripQStyle::CE_SizeGripusesQStyle::drawControl()
PE_CheckMarkQStyle::PE_IndicatorMenuCheckMark
PE_ScrollBarAddLineQStyle::CE_ScrollBarAddLineusesQStyle::drawControl()
PE_ScrollBarSubLineQStyle::CE_ScrollBarSubLineusesQStyle::drawControl()
PE_ScrollBarAddPageQStyle::CE_ScrollBarAddPageusesQStyle::drawControl()
PE_ScrollBarSubPageQStyle::CE_ScrollBarSubPageusesQStyle::drawControl()
PE_ScrollBarSliderQStyle::CE_ScrollBarSliderusesQStyle::drawControl()
PE_ScrollBarFirstQStyle::CE_ScrollBarFirstusesQStyle::drawControl()
PE_ScrollBarLastQStyle::CE_ScrollBarLastusesQStyle::drawControl()
PE_ProgressBarChunkQStyle::PE_IndicatorProgressChunk
PE_PanelLineEditQStyle::PE_FrameLineEdit
PE_PanelTabWidgetQStyle::PE_FrameTabWidget
PE_WindowFrameQStyle::PE_FrameWindow
PE_CheckListControllerQStyle::PE_Q3CheckListController
PE_CheckListIndicatorQStyle::PE_Q3CheckListIndicator
PE_CheckListExclusiveIndicatorQStyle::PE_Q3CheckListExclusiveIndicator
PE_PanelGroupBoxQStyle::PE_FrameGroupBox
PE_TreeBranchQStyle::PE_IndicatorBranch
PE_RubberBandQStyle::CE_RubberBandusesQStyle::drawControl()
PE_PanelToolBarQStyle::PE_PanelToolBar
PE_ToolBarHandleQStyle::PE_IndicatorToolBarHandle
PE_ToolBarSeparatorQStyle::PE_IndicatorToolBarSeparator

The QStyle::drawControlMask() and QStyle::drawComplexControlMask() functions have been removed. They are replaced with a style hint.

The QStyle::drawItem() overloads that took both a pixmap and a string have been removed. UseQStyle::drawItemText() andQStyle::drawItemPixmap() directly.

The QStyle::itemRect() overload that took both a pixmap and a string is also removed, use eitherQStyle::itemTextRect() orQStyle::itemPixmapRect() instead.

QStyleSheet

TheQStyleSheet and QStyleSheetItem classes have been renamedQ3StyleSheet andQ3StyleSheetItem, and have been moved to theQt3Support library.

SeeRich Text Processing for an overview of the Qt 4 rich text classes, andQt Style Sheets for a description of CSS-like style sheet support in Qt 4.2 and above.

QSyntaxHighlighter

TheQSyntaxHighlighter class from Qt 3 has been renamedQ3SyntaxHighlighter and moved to theQt3Support library. Since Qt 4.1, it has been replaced by a newQSyntaxHighlighter class based on Qt 4's new rich text engine.

QTabBar

SeeProperties for a list ofQTabBar properties in Qt 3 that have changed in Qt 4.

QTabDialog

TheQTabDialog class is no longer part of the public Qt API. It has been renamedQ3TabDialog and moved toQt3Support. In Qt 4 applications, you can easily obtain the same result by combining aQTabWidget with aQDialog and provideQPushButtons yourself.

See also thedialogs/tabdialog example, which shows how to implement tab dialogs in Qt 4.

QTabWidget

SeeProperties for a list ofQTabWidget properties in Qt 3 that have changed in Qt 4.

QTable

TheQTable,QTableItem,QComboTableItem,QCheckTableItem, andQTableSelection classes have been renamedQ3Table,Q3TableItem,Q3ComboTableItem,Q3CheckTableItem, andQ3TableSelection and moved to theQt3Support library. New Qt applications should use the newQTableWidget orQTableView class instead.

Some of these classes behave differently with respect to the way they handleNULL pointers. For example,Q3TableItem::setPixmap() no longer acceptsNULL or 0 to indicate that the item should contain a null pixmap; in this case, a null pixmap should be constructed and passed explicitly to the function.

SeeModel/View Programming for an overview of the new item view classes.

QTextCodec

The loadCharmap() and loadCharmapFromFile() functions are no longer available in Qt 4. You need to create your own codec if you want to create a codec based on a POSIX2 charmap definition.

QTextDrag

TheQTextDrag class has been renamedQ3TextDrag and moved to theQt3Support library. In Qt 4, useQMimeData instead and callQMimeData::setText() to set the data.

SeePorting to Qt 4 - Drag and Drop for a comparison between the drag and drop APIs in Qt 3 and Qt 4.

QTextEdit

The oldQTextEdit andQTextBrowser classes have been renamedQ3TextEdit andQ3TextBrowser, and have been moved toQt3Support. The newQTextEdit andQTextBrowser have a somewhat different API.

TheQTextEdit::setWrapPolicy() function has been renamed tosetWordWrapMode() and theQTextEdit::setWrapColumnOrWidth() function has been renamed tosetLineWrapColumnOrWidth(). TheQ3TextEdit::setWrapPolicy() andQ3TextEdit::setWrapColumnOrWidth() still provide this functionality in theQ3TextEdit class.

SeeRich Text Processing for an overview of the Qt 4 rich text classes.

QTextIStream

TheQTextIStream convenience class is no longer provided in Qt 4. UseQTextStream directly instead.

QTextOStream

TheQTextOStream convenience class is no longer provided in Qt 4. UseQTextStream directly instead.

QTextOStreamIterator

The undocumentedQTextOStreamIterator 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.

QTextStream

QTextStream has undergone a number of API and implementation enhancements, and some of the changes affectQTextStream's behavior:

  • QTextStream now uses buffered writing, which means that you need to callQTextStream::flush(), or use the streaming manipulatorsendl orflush if you needQTextStream to flush its write buffer. The stream is flushed automatically ifQTextStream is deleted or when the device is closed.
  • QTextStream now uses buffered reading, so if you read a line from the stream,QTextStream will read as much as it can from the device to fill up its internal read buffer. This speeds up reading significantly, but Qt 3 code that mixedQTextStream access and direct device access may need to be updated.
  • WhileQTextStream in Qt 3 always translated end-of-line characters from Windows style ("\r\n") to Unix style ("\n") on Windows,QTextStream in Qt 4 only does this on devices opened with theQIODevice::Text mode (formerlyIO_Translate).

Note that when using aQTextStream on aQFile in Qt 4, callingQIODevice::reset() on theQFile will not have the expected result becauseQTextStream now buffers the file. Use theQTextStream::seek() function instead.

QTextView

TheQTextView class has been renamedQ3TextView and moved to theQt3Support library.

QTimeEdit

TheQTimeEdit class in Qt 4 is a convenience class based onQDateTimeEdit. The old class has been renamedQ3TimeEdit and moved to theQt3Support library.

SeeVirtual Functions for a list ofQTimeEdit virtual member functions in Qt 3 that are no longer virtual in Qt 4.

QTimer

Windows restricts the granularity of timers, but starting with Qt 4, we emulate a finer time resolution. On Windows XP we use the multimedia timer API, which gives us 1 millisecond resolution forQTimer.

Note that Windows 2000 has a lower timer resolution, and that code relying on underlying system timer restrictions encounters no such limitations using Qt 4 (e.g., setting an interval of 0 millisecond results in Qt occupying all of the processor time when no GUI events need processing).

QToolBar

The oldQToolBar class, which worked with the oldQMainWindow andQDockArea classes and inherited fromQDockWindow, has been renamedQ3ToolBar and moved toQt3Support. Note that, when usingQ3ToolBar, the toolbar's actions must beQ3Actions.

Use the newQToolBar class in new applications.

Note:Q3ToolBar'shorizontallyStretchable property can be achieved inQToolBar withsize policies.

QToolButton

SeeProperties for a list ofQToolButton properties in Qt 3 that have changed in Qt 4.

Note that many of the properties that could previously be set in the constructor must now be set separately.

QToolTip

The QToolTip::setGloballyEnabled() function no longer exists. Tooltips can be disabled byinstalling an event filter onqApp (the uniqueQApplication object) to block events of typeQEvent::ToolTip.

QUriDrag

TheQUriDrag class has been renamedQ3UriDrag and moved to theQt3Support library. In Qt 4, useQMimeData instead and call QMimeData::setUrl() to set the URL.

SeePorting to Qt 4 - Drag and Drop for a comparison between the drag and drop APIs in Qt 3 and Qt 4.

QUrl

TheQUrl class has been rewritten from scratch in Qt 4 to be more standard-compliant. The oldQUrl class has been renamedQ3Url and moved to theQt3Support library.

The newQUrl class provides an extensive list of compatibility functions to ease porting fromQ3Url toQUrl. A few functions require you to change your code:

QUrlOperator

TheQUrlOperator class is no longer part of the public Qt API. It has been renamed Q3UrlOperator and moved toQt3Support.

From Qt 4.4, the Network Access API provides a subset of the features provided byQUrlOperator that are mostly intended for use with applications that use the HTTP and FTP protocols. See theQNetworkRequest,QNetworkReply, andQNetworkAccessManager documentation for further details.

QValueList<T>

The QValueList<T> class has been replaced byQList<T> andQLinkedList<T> in Qt 4. As a help when porting older Qt applications, theQt3Support library contains a QValueList<T> class implemented in terms of the newQLinkedList<T>. Similarly, it contains QValueListIterator<T> and QValueListConstIterator<T> classes implemented in terms ofQLinkedList<T>::iterator andQLinkedList<T>::const_iterator.

When porting to Qt 4, you have the choice of usingQList<T> orQLinkedList<T> as alternatives to QValueList<T>.QList<T> has an index-based API and provides very fast random access (QList::operator[]), whereasQLinkedList<T> has an iterator-based API.

Here's a list of problem functions:

  • QValueList(const std::list<T> &) doesn't exist inQList orQLinkedList. You can simulate it by callingappend() in a loop.
  • QValueList::insert(iterator, size_type, const T& x) doesn't exist inQList orQLinkedList. Callinsert() repeatedly instead.
  • QValueList::fromLast() doesn't exist inQList orQLinkedList. Use QValueList::end() instead.

    For example, if you have code like

        for (QValueList<T>::iterator i = list.fromLast(); i != list.begin(); --i)        do_something(*i);

    you can rewrite it as

    QLinkedList<T>::iterator i= list.end();while (i!= list.begin()) {--i;// decrement i before using it        do_something(*i);    }
  • QValueList::append() and QValueList::prepend() return an iterator to the inserted item.QList's andQLinkedList's corresponding functions don't, but it's not a problem because QValueList::prepend() always returns begin() and append() always returns QValueList::end() - 1.
  • QValueList::at(i) return an iterator to the item at indexi. This corresponds toQList::begin() +i.
  • QValueList::contains(const T &) corresponds toQList::count(const T &) andQLinkedList::count(const T &).

QValueVector<T>

The QValueVector<T> class has been replaced byQVector<T> in Qt 4. As a help when porting older Qt applications, theQt3Support library contains aQ3ValueVector<T> class implemented in terms of the newQVector<T>.

When porting from QValueVector<T> toQVector<T>, you might run into the following incompatibilities:

  • QValueVector(const std::vector<T> &) doesn't exist inQVector. You can simulate it by callingQVector::append()} in a loop.
  • QValueVector::resize(int, const T &) doesn't exist inQVector. If you want the new items to be initialized with a particular value, useQVector::insert() instead.
  • QValueVector::at() on a non-const vector returns a non-const reference. This corresponds to QVector::operator[]().
  • Both QValueVector::at() functions have anok parameter of typebool * that is set to true if the index is within bounds. This functionality doesn't exist inQVector; instead, check the index againstQVector::size() yourself.

SeeContainer Classes for an overview of the Qt 4 container classes.

QVariant

Some changes to the rest of the Qt library have implications onQVariant:

  1. TheQVariant::ColorGroup enum value is defined only ifQT3_SUPPORT is defined.
  2. TheQVariant::IconSet enum value has been renamedQVariant::Icon.
  3. TheQVariant::CString enum value is now a synonym forQVariant::ByteArray.

Also, theQVariant(bool, int) constructor has been replaced byQVariant(bool). Old code likeQVariant(true, 0) should be replaced withQVariant(true); otherwise, theQVariant(int, void *) overload might accidentally be triggered.

Many ofQVariant's convenience functions in Qt 3, such as toColor() and toKeySequence(), have been removed to enableQVariant to be part of theQtCore module.QVariant is still able to hold values of these types.

Types which are not supported by any of theQVariant constructors can be stored as variants with theQVariant::fromValue() function. Types with no suitable convenience function for unpacking can be retrieved with theQVariant::value() function or passed directly to classes that implement the QVariant() operator.

Qt 3 functionQt 4 function
toBitmap ()QVariant::value()
toBrush ()QVariant::value()
toColorGroup ()UseQVariant::value() withQPalette instead.
toColor ()QVariant::value()
toCString ()QVariant::toByteArray()
toCursor ()QVariant::value()
toFont ()QVariant::value()
toIconSet ()UseQVariant::value() withQIcon instead.
toImage ()QVariant::value()
toKeySequence ()QVariant::value()
toPalette ()QVariant::value()
toPen ()QVariant::value()
toPixmap ()QVariant::value()
toPointArray ()QVariant::value()
toRegion ()QVariant::value()
toSizePolicy ()QVariant::value()

See theQVariant::Type enum for a list of types supported byQVariant.

QVBox

TheQVBox class is now only available asQ3VBox in Qt 4. You can achieve the same result asQVBox by creating aQWidget with a vertical layout:

For example, if you have code like

QVBox *vbox = new QVBox;QPushButton *child1 = new QPushButton(vbox);QPushButton *child2 = new QPushButton(vbox);

you can rewrite it as

QWidget*vbox=newQWidget;QPushButton*child1=newQPushButton;QPushButton*child2=newQPushButton;QVBoxLayout*layout=newQVBoxLayout;layout->addWidget(child1);layout->addWidget(child2);vbox->setLayout(layout);

Note that child widgets are not automatically placed into the widget's layout; you will need to manually add each widget to theQVBoxLayout.

QVGroupBox

TheQVGroupBox class has been renamedQ3VGroupBox and moved to theQt3Support library. Qt 4 does not provide a specific replacement class forQVGroupBox sinceQGroupBox is designed to be a generic container widget. As a result, you need to supply your own layout for any child widgets.

See#QGroupBox for more information about porting code that uses group boxes.

QWhatsThis

TheQWhatsThis class has been redesigned in Qt 4. The oldQWhatsThis class is available asQ3WhatsThis inQt3Support.

QWidget Class

Widget background painting has been greatly improved, supporting flicker-free updates and making it possible to have semi-transparent widgets. This renders the following background handling functions obsolete:

Sample code on how to do obtain similar behavior from Qt 4, previously handled by some of the above functions can be found in theQt 3 Support Members for QWidget page.

A widget now receives change events in itsQWidget::changeEvent() handler. This makes the following virtual change handlers obsolete:

The following functions were slots, but are no more:

The following functions were incorrectly marked as virtual:

The internal clearWState() function was removed. UseQWidget::setAttribute() instead.

setWFlags() was renamedQWidget::setWindowFlags().

clearWFlags() has no direct replacement. You can useQWidget::setAttribute() instead. For example,setAttribute(..., false) to clear an attribute. More information <<<<<<< HEAD is availablehere. ======= is availablehere. >>>>>>> c61eb6d... WIP: Changes needed to build 4.8 docs using latest version of QDoc

testWFlags() was renamed totestAttribute().

SeeProperties for a list ofQWidget properties in Qt 3 that have changed in Qt 4.

QWidgetFactory

TheQWidgetFactory class has been replaced byQFormBuilder in Qt 4.

QWidgetIntDict

TheQWidgetIntDict class was a synonym for QIntDict<QWidget>. It is no longer available in Qt 4. If you link againstQt3Support, you can useQ3IntDict<QWidget> instead; otherwise, see thesection on QDict<T>.

QWidgetList

In Qt 3, theQWidgetList class was a typedef for QPtrList<QWidget>. In Qt 4, it is a typedef forQList<QWidget *>. See thesection on QPtrList<T>.

QWidgetPlugin

TheQWidgetPlugin class is no longer available in Qt 4. To create custom widget plugins, subclassQDesignerCustomWidgetInterface to provide information about the custom widget, and build a plugin in the way described in theCustom Widget Plugin example.

QWidgetStack

TheQWidgetStack class is no longer part of the Qt public API. It has been renamedQ3WidgetStack and moved toQt3Support. In Qt 4 applications, you can useQStackedWidget instead to obtain the same results.

QWizard

TheQWizard class was reintroduced in Qt 4.3. See theTrivial Wizard Example,License Wizard Example andClass Wizard Example for more details.

QWorkspace

TheQWorkspace in Qt 4 class requires explicit adding of MDI windows withQWorkspace::addWindow().

Porting GuidesPorting to Qt 4 - Virtual Functions

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp