Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Porting to Qtopia 4

This page suplements the more general information for Porting Between Qtopia/Qt Extended Versions.

Basic Conversions

If a previously used Qt function is not available and is not listed below or in the above documents, check if it is declared in the relevant header file, but within #ifdef QT3_SUPPORT bracketing.

If it is, check the in-line code for the function for the corresponding Qt 4 code.

For example:

QComboBox::setCurrentItem(int) is in Qt3_SUPPORT, but it is an in-line function that simply calls the renamed function, QComboBox::setCurrentIndex(int).

The table below lists the function conversions for porting to Qtopia 4.

Qtopia 2Qtopia 4
AppLnkQContent and QContentSet
ContextBarQSoftMenuBar
ContextMenuQMenu and QSoftMenuBar::addMenuTo()
DocLnkQContent and QContentSet
FileSelectorQDocumentSelector
Global::decodeBase64(bytearray)QByteArray::fromBase64()
Global::encodeBase64(bytearray)QByteArray::toBase64()
ImageSelectorQImageDocumentSelector
QArrayQList
QCStringQString or QByteArray.

Note: QCopChannel connections use QString

QColorGroup::base()QPalette::color(QPalette::Base)
QDataStream::ds(bytearray, QIODevice::ReadOnly)QDataStream::ds(bytearray) - it is always read only
QDialog::dlg(parent,name,modal)QDialog::dlg(parent,name); QDialog::dlg.setModal(TRUE)
QDir::cleanDirPath()QDir::cleanPath()
QFileInfo::dirPath()QFileInfo::absolutePath()
QFileInfo::extension()QFileInfo::completeSuffix()
QIconViewQListView.
QList::remove()QList::removeAll()
QList<T>QList<T*>
QListBoxQListView
QListIterator<T>QList<T>::iterator; also consider using foreach
QListViewQTreeView if hierarchical, otherwise QListView
QPEApplicationQtopiaApplication
QPEToolBarQToolBar
QScrollViewQScrollArea
QValueListQList
Qtopia::escapeMultiLineStringQt::convertFromPlainText()
Qtopia::escapeStringQt::escape()
StorageInfoQFileSystem and QStorageMetaInfo
Sound::soundAlarm()Qtopia::soundAlarm()

Qtopia 4 Headers

Qtopia 4 has both classic (2.2-style) and Qt-style headers. The classic headers are provided to ease porting but you should consider switching to Qt-style headers to avoid dependency problems and because they will eventually be removed.

There are 2 ways to include Qt-style headers. You can use the class name (for public classes in public headers) or the header file name.

    #include <QAppointment>
    #include <qappointment.h>
    #include <private/vobject_p.h>

Note that the classic versions of these headers are.

    #include <qtopia/pim/qappointment.h>
    #include <qtopia/pim/private/vobject_p.h>

In cases where a header with the same name exists in 2 libraries you may need to prefix the library name.

    #include <qtopiapim/QAppointment>
    #include <qtopiapim/qappointment.h>
    #include <qtopiapim/private/vobject_p.h>

However, this should be avoided where possible because it can lead to dependency problems. If you include <QAppointment> but you have not declared your dependency on libqtopiapim (depends(libraries/qtopiapim)) you will get a compile error that will clearly identify the header <QAppointment> is unavailable. If you include <qtopiapim/QAppointment> you will get a linker or runtime error that may not indicate the problem in a clear way.

Designer and UIC

UIC can convert Qt 2/3 UI files to Qt 4, however, it generates code that uses Qt 3 support classes if the .ui file specifies either a class or a property on a class which is in the Qt 3 Support module.

For example, if QButtonGroup is used, it will generally convert trivially to QButtonGroup which is also in Qt 4, however, QButtonGroup in Qt 3 inherited QGroupBox which in turn inherited QFrame. So if the .ui file specifies QFrame properties on a QButtonGroup, then Qt 3 Support code will be generated.

To port .ui files:

  • Run: uic3 -convert oldfile.ui >newfile.ui
  • Edit/check newfile.ui - for example class names may have been lowercased MyDialog -> mydialog
  • Remove use of Qt 3 support classes (look for "Q3"), and use Qt 4 classes as described above.

Note: converted .ui files contain an objectName property that matches the widget's name. While there may be a few cases where an objectName should be set, most cases are redundant and just take up space. You may choose to remove this property (in Designer or by editing the .ui file).

QProcess

QProcess is now subclassed from QIODevice, so instead of readStderr() and read|writeStdin() you access output as follows:

       myproc.setInputChannel( QProcess::StandardOutput );
       QTextStream procstream( myproc );
       procStream >> theResults;  // get into a string
       myproc.setInputChannel( QProcess::StandardError );
       procStream >> someError;

There is also readAllStandardError(), and to write to stdin, there are the QIODevice methods, such as myproc.write(<some text>).

The signal wroteToStdin() should be replaced by usage of QIODevice::bytesWritten(int).

QMenu and QActionGroup

Mutually exclusive checkable menu items are implemented with QActionGroup.

Note: addAction() is now a method of QWidget:

        QMenu* menu = new QMenu;
        menu->setCheckable( TRUE );
        QActionGroup *grp = new QActionGroup;
        for (int i = 0; i <= myLastItem; ++i )
        {
            items[i] = new QAction( QString( "option %1" ).arg( i ), grp );
            items[i]->setCheckable( TRUE );
        }
        items[myDefault]->setChecked( TRUE );
        menu->addActions( grp->actions() );

QAction for Regular Menu Items

In the past, you may have used something like the following to create regular menu items:

    a_settings = new QAction( tr("Settings..."),
                              theicon,
                              QString::null, 0, this, 0 );
    connect( a_settings, SIGNAL( activated() ),
             this, SLOT( doSettings() ) );
    a_settings->addTo( menu );

The new sequence looks like this:

    a_settings = new QAction( theicon,
                              tr("Settings..."), this );
    connect( a_settings, SIGNAL( triggered() ),
             this, SLOT( doSettings() ) );
    menu->addAction( a_settings );

Note: the transposition of the first two arguments to the QAction constructor, and the use of the triggered() slot rather than activated().

QImage/QPixmap::smoothScale

Qt 2 code:

        img = img.smoothScale( 5, 5 );

becomes:

        img.scale( 5, 5, Qt::KeepAspectRatio, Qt::SmoothTransformation );

QStyle

In tune with other parts of Qt, query and paint methods are now parameterized by enums instead of having specific names. Search the QStyle documentation for the name you want to query or paint, to find the enum and the method you need.

Qt 2 code:

    QRect r = style().pushButtonContentsRect( this );
    int sx, sy;
    style().getButtonShift(sx, sy);
    int dx = style().menuButtonIndicatorWidth( height() );
    style().drawArrow( p, DownArrow, FALSE, x+w-dx, y+2, dx-4, h-4,
             colorGroup(), isEnabled() );

becomes:

    QStyleOptionButton sob;
    sob.init( this );  // copies this->rect() and this->state, this's StyleFlags
    QRect r = style()->subRect( QStyle::SR_PushButtonContents, &sob );
    int sx = style()->pixelMetric( QStyle::PM_ButtonShiftHorizontal, &sob );
    int sy = style()->pixelMetric( QStyle::PM_ButtonShiftVertical, &sob );
    int dx = style()->pixelMetric( QStyle::PM_MenuButtonIndicator, &sob );
    QStyleOptionButton arrowStyle = sob;
    arrowStyle.rect.setLeft( sob.rect.right() - h) );  // a small square at RHS
    style()->drawPrimitive( QStyle::PE_IndicatorArrowDown, &arrowStyle, p );

QCanvas

There is no QCanvas in Qt 4 (it is in the unavailable Qt 3 Support module), but it is available in Qtopia 4 - instead of including qcanvas.h or Qt/qcanvas.h, use qtopia/canvas/qcanvas.h.

However, note that this class is intended to be obsoleted in Qtopia 4.2 by a new Qt class.

QUuid

QUuid is in Qt 4, so include Qt/quuid.h, not qtopia/quuid.h.

Plug-ins

Qtopia 4 uses the standard Qt 4 mechanisms for plug-ins.

The code below shows the pattern used for Qtopia plug-ins. Replace MyPlugin with the name of the type of plug-in you are writing,such as InputMethod. The pure virtual functions are those functions you want your plug-in to provide and the keys function should return the name of the plug-in implementation. For example, keys() would return Handwriting for the handwriting plug-in, or Handwriting, Fullscreen Handwriting if both plug-ins are provided).

    #include <qplugin.h>
    #include <qfactoryinterface.h>
    #include <qobject.h>

    struct QMyPluginFactoryInterface : public QFactoryInterface
    {
        // pure virtual functions
    };

    Q_DECLARE_INTERFACE(QMyPluginFactoryInterface, "http://trolltech.com/Qtopia/QMyPluginFactoryInterface")

    class QMyPluginPlugin : public QObject, public QMyPluginFactoryInterface
    {
        Q_OBJECT
        Q_INTERFACES(QMyPluginFactoryInterface:QFactoryInterface)
    public:
        QMyPluginPlugin(QObject *parent=0);
        ~QMyPluginPlugin();

        virtual QStringList keys() const = 0;
        // pure virtual functions
    };

Resource

Resources are now found using the Qt 4 QFileEngine mechanism, where in all places where a filename may be used, a special name starting with a colon (":") is used instead to refer to a resource. In Qt this is only used to refer to compiled-in resources, but in Qtopia, they may be actual files in predetermined places in the filesystem, that is, as Resource provided in Qtopia 2.

Qtopia 2Qtopia 4
Resource::loadPixmap("open")QPixmap(":image/open")
Resource::loadIconSet("add")QIcon(":icon/add")
Resource::findPixmap("addressbook/homephone")":image/addressbook/homephone"
Resource::findPixmap("new")":image/new"
<img src="addressbook/home.png"><img src=":icon/addressbook/home">

You can use scripts/porting-resources to automate the changes.

Config

Use QSettings instead.

Where Config files include translations (i.e. keys with []) and you need to read those keys, use QTranslatableSettings instead.

Rather than Config::setGroup(), you should use QSettings::beginGroup()..endGroup() spans.

Note:

  • Config only used end-of-line for string termination.
  • QSettings has different quoting rules. Where Config contains quotes ("), this should be considered.
  • Config::isValid() was FALSE if the file did not yet exist, whereas QSettings::status() is TRUE.

You can use scripts/porting-config to automate the changes, however:

Note: clever use of Config::setGroup() can confuse that script.

The settings files are now stored in ~/Settings/Trolltech/ or $QPEDIR/etc/default/Trolltech/.

VScrollView

Use QScrollArea instead.

Keypad mode will work correctly provided you set the focus policy of QScrollArea to Qt::NoFocus.

For example:

        QScrollArea *sa = new QScrollArea(...);
        sa->setFocusPolicy(Qt::NoFocus);
        QWidget *view = new QWidget;
        sa->setWidget(view);
        sa->setWidgetResizable(true);
        // add children to view.

grabKeyboard() and ungrabKeyboard()

QtopiaApplication::grabKeyboard() and QtopiaApplication::ungrabKeyboard()

The documentation use to say:

    Grabs the physical keyboard keys, e.g. the application's launching
    keys. Instead of launching applications when these keys are pressed
    the signals emitted are sent to this application instead. Some games
    programs take over the launch keys in this way to make interaction
    easier.

    Under Qtopia Phone Edition this function does nothing. It is not
    possible to grab the keyboard under Qtopia Phone Edition.

Any calls to these methods can be safely removed. They did nothing since the PDA edition code was taken away when #ifdef QTOPIA_PHONE was removed.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 73
  2. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  3. Une nouvelle ère d'IHM 3D pour les automobiles, un concept proposé par Digia et implémenté avec Qt 3
  4. Qt Creator 2.5 est sorti en beta, l'EDI supporte maintenant plus de fonctionnalités de C++11 2
  5. Vingt sociétés montrent leurs décodeurs basés sur Qt au IPTV World Forum, en en exploitant diverses facettes (déclaratif, Web, widgets) 0
  6. PySide devient un add-on Qt et rejoint le Qt Project et le modèle d'open gouvernance 1
  7. Thread travailleur avec Qt en utilisant les signaux et les slots, un article de Christophe Dumez traduit par Thibaut Cuvelier 1
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 102
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 53
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 73
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 229
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
  7. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 101
Page suivante

Le Qt Quarterly au hasard

Logo

Algorithmes génériques

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt qtextended4.4
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web