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  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

Listboxes and Comboboxes

This example program demonstrates how to use listboxes (with single selection and multi selection) and comboboxes (editable and non-editable).


Header file:

/****************************************************************************
** $Id: qt/listboxcombo.h   3.3.7   edited Aug 31 2005 $
**
** Copyright (C) 1992-2005 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef LISTBOX_COMBO_H
#define LISTBOX_COMBO_H

#include <qvbox.h>

class QListBox;
class QLabel;

class ListBoxCombo : public QVBox
{
    Q_OBJECT

public:
    ListBoxCombo( QWidget *parent = 0, const char *name = 0 );

protected:
    QListBox *lb1, *lb2;
    QLabel *label1, *label2;

protected slots:
    void slotLeft2Right();
    void slotCombo1Activated( const QString &s );
    void slotCombo2Activated( const QString &s );

};

#endif


Implementation:

/****************************************************************************
** $Id: qt/listboxcombo.cpp   3.3.7   edited Aug 31 2005 $
**
** Copyright (C) 1992-2005 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "listboxcombo.h"

#include <qcombobox.h>
#include <qlistbox.h>
#include <qhbox.h>
#include <qpushbutton.h>
#include <qstring.h>
#include <qpixmap.h>
#include <qlabel.h>
#include <qimage.h>
#include <qpainter.h>
#include <qstyle.h>


class MyListBoxItem : public QListBoxItem
{
public:
    MyListBoxItem()
        : QListBoxItem()
    {
        setCustomHighlighting( TRUE );
    }

protected:
    virtual void paint( QPainter * );
    virtual int width( const QListBox* ) const { return 100; }
    virtual int height( const QListBox* ) const { return 16; }

};

void MyListBoxItem::paint( QPainter *painter )
{
    // evil trick: find out whether we are painted onto our listbox
    bool in_list_box = listBox() && listBox()->viewport() == painter->device();

    QRect r ( 0, 0, width( listBox() ), height( listBox() ) );
    if ( in_list_box && isSelected() )
        painter->eraseRect( r );
    painter->fillRect( 5, 5, width( listBox() ) - 10, height( listBox() ) - 10, Qt::red );
    if ( in_list_box && isCurrent() )
        listBox()->style().drawPrimitive( QStyle::PE_FocusRect, painter, r, listBox()->colorGroup() );
}

/*
 * Constructor
 *
 * Creates child widgets of the ListBoxCombo widget
 */

ListBoxCombo::ListBoxCombo( QWidget *parent, const char *name )
    : QVBox( parent, name )
{
    setMargin( 5 );
    setSpacing( 5 );

    unsigned int i;
    QString str;

    QHBox *row1 = new QHBox( this );
    row1->setSpacing( 5 );

    // Create a multi-selection ListBox...
    lb1 = new QListBox( row1 );
    lb1->setSelectionMode( QListBox::Multi );

    // ...insert a pixmap item...
    lb1->insertItem( QPixmap( "qtlogo.png" ) );
    // ...and 100 text items
    for ( i = 0; i < 100; i++ ) {
        str = QString( "Listbox Item %1" ).arg( i );
        if ( !( i % 4 ) )
            lb1->insertItem( QPixmap( "fileopen.xpm" ), str );
        else
            lb1->insertItem( str );
    }

    // Create a pushbutton...
    QPushButton *arrow1 = new QPushButton( " -> ", row1 );
    // ...and connect the clicked SIGNAL with the SLOT slotLeft2Right
    connect( arrow1, SIGNAL( clicked() ), this, SLOT( slotLeft2Right() ) );

    // create an empty single-selection ListBox
    lb2 = new QListBox( row1 );

    QHBox *row2 = new QHBox( this );
    row2->setSpacing( 5 );

    QVBox *box1 = new QVBox( row2 );
    box1->setSpacing( 5 );

    // Create a non-editable Combobox and a label below...
    QComboBox *cb1 = new QComboBox( FALSE, box1 );
    label1 = new QLabel( "Current Item: Combobox Item 0", box1 );
    label1->setMaximumHeight( label1->sizeHint().height() * 2 );
    label1->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    //...and insert 50 items into the Combobox
    for ( i = 0; i < 50; i++ ) {
        str = QString( "Combobox Item %1" ).arg( i );
        if ( i % 9 )
            cb1->insertItem( str );
        else
            cb1->listBox()->insertItem( new MyListBoxItem );
    }

    QVBox *box2 = new QVBox( row2 );
    box2->setSpacing( 5 );

    // Create an editable Combobox and a label below...
    QComboBox *cb2 = new QComboBox( TRUE, box2 );
    label2 = new QLabel( "Current Item: Combobox Item 0", box2 );
    label2->setMaximumHeight( label2->sizeHint().height() * 2 );
    label2->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    // ... and insert 50 items into the Combobox
    for ( i = 0; i < 50; i++ ) {
        str = QString( "Combobox Item %1" ).arg( i );
        if ( !( i % 4 ) )
            cb2->insertItem( QPixmap( "fileopen.xpm" ), str );
        else
            cb2->insertItem( str );
    }

    // Connect the activated SIGNALs of the Comboboxes with SLOTs
    connect( cb1, SIGNAL( activated( const QString & ) ), this, SLOT( slotCombo1Activated( const QString & ) ) );
    connect( cb2, SIGNAL( activated( const QString & ) ), this, SLOT( slotCombo2Activated( const QString & ) ) );
}

/*
 * SLOT slotLeft2Right
 *
 * Copies all selected items of the first ListBox into the
 * second ListBox
 */

void ListBoxCombo::slotLeft2Right()
{
    // Go through all items of the first ListBox
    for ( unsigned int i = 0; i < lb1->count(); i++ ) {
        QListBoxItem *item = lb1->item( i );
        // if the item is selected...
        if ( item->isSelected() ) {
            // ...and it is a text item...
            if ( item->pixmap() && !item->text().isEmpty() )
                lb2->insertItem( *item->pixmap(), item->text() );
            else if ( !item->pixmap() )
                lb2->insertItem( item->text() );
            else if ( item->text().isEmpty() )
                lb2->insertItem( *item->pixmap() );
        }
    }
}

/*
 * SLOT slotCombo1Activated( const QString &s )
 *
 * Sets the text of the item which the user just selected
 * in the first Combobox (and is now the value of s) to
 * the first Label.
 */

void ListBoxCombo::slotCombo1Activated( const QString &s )
{
    label1->setText( QString( "Current Item: %1" ).arg( s ) );
}

/*
 * SLOT slotCombo2Activated( const QString &s )
 *
 * Sets the text of the item which the user just selected
 * in the second Combobox (and is now the value of s) to
 * the second Label.
 */

void ListBoxCombo::slotCombo2Activated( const QString &s )
{
    label2->setText( QString( "Current Item: %1" ).arg( s ) );
}


Main:

/****************************************************************************
** $Id: qt/main.cpp   3.3.7   edited Aug 31 2005 $
**
** Copyright (C) 1992-2005 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "listboxcombo.h"
#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    ListBoxCombo listboxcombo;
    listboxcombo.resize( 400, 270 );
    listboxcombo.setCaption( "Qt Example - Listboxes and Comboboxes" );
    a.setMainWidget( &listboxcombo );
    listboxcombo.show();

    return a.exec();
}

See also Examples.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 64
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le Qt Developer Network au hasard

Logo

Extension de Qt WebKit

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. 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 3.3
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