C++/Qt/QStringList — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Версия 17:21, 25 мая 2010

Adding QStringList to QListWidget

<source lang="cpp"> /*

* Copyright (c) 2006-2007, Johan Thelin
* 
* All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
* 
*     * Redistributions of source code must retain the above copyright notice, 
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice,  
*       this list of conditions and the following disclaimer in the documentation 
*       and/or other materials provided with the distribution.
*     * Neither the name of APress nor the names of its contributors 
*       may be used to endorse or promote products derived from this software 
*       without specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
  1. include "listwidgetdialog.h"
  2. include <QListWidget>
  3. include <QPushButton>
  4. include <QGridLayout>

ListWidgetDialog::ListWidgetDialog() : QDialog(0) {

 QPushButton *left, *right;
 QGridLayout *layout = new QGridLayout( this );
 layout->addWidget( left = new QPushButton( "<<" ), 0, 1 );
 layout->addWidget( right = new QPushButton( ">>" ), 1, 1 );
 layout->addWidget( leftList = new QListWidget(), 0, 0, 3, 1 );
 layout->addWidget( rightList = new QListWidget(), 0, 2, 3, 1 );
 
 connect( left, SIGNAL(clicked()), this, SLOT(moveLeft()) );
 connect( right, SIGNAL(clicked()), this, SLOT(moveRight()) );
 QStringList items;
 items << "Argentine" << "Brazilian" << "South African" 
       << "USA West" << "Monaco" << "Belgian" << "Spanish" 
       << "Swedish" << "French" << "British" << "German" 
       << "Austrian" << "Dutch" << "Italian" << "USA East" 
       << "Canadian";  
 leftList->addItems( items );

}

void ListWidgetDialog::moveLeft() {

 if( rightList->selectedItems().count() != 1 )
   return;
   
 QListWidgetItem *item = rightList->takeItem( rightList->currentRow() );
 leftList->addItem( item );

} void ListWidgetDialog::moveRight() {

 if( leftList->selectedItems().count() != 1 )
   return;
   
 QListWidgetItem *item = leftList->takeItem( leftList->currentRow() );
 rightList->addItem( item );

}

Chapter03\listwidget\listwidgetdialog.h /*

* Copyright (c) 2006-2007, Johan Thelin
* 
* All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
* 
*     * Redistributions of source code must retain the above copyright notice, 
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice,  
*       this list of conditions and the following disclaimer in the documentation 
*       and/or other materials provided with the distribution.
*     * Neither the name of APress nor the names of its contributors 
*       may be used to endorse or promote products derived from this software 
*       without specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
  1. ifndef LISTWIDGETDIALOG_H
  2. define LISTWIDGETDIALOG_H
  3. include <QDialog>

class QListWidget; class ListWidgetDialog : public QDialog {

 Q_OBJECT
 

public:

 ListWidgetDialog();
 

public slots:

 void moveLeft();
 void moveRight();
 

private:

 QListWidget *leftList;
 QListWidget *rightList;

};

  1. endif // LISTWIDGETDIALOG_H

Chapter03\listwidget\main.cpp /*

* Copyright (c) 2006-2007, Johan Thelin
* 
* All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
* 
*     * Redistributions of source code must retain the above copyright notice, 
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice,  
*       this list of conditions and the following disclaimer in the documentation 
*       and/or other materials provided with the distribution.
*     * Neither the name of APress nor the names of its contributors 
*       may be used to endorse or promote products derived from this software 
*       without specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
  1. include <QApplication>
  2. include "listwidgetdialog.h"

int main( int argc, char **argv ) {

 QApplication app( argc, argv );
 
 ListWidgetDialog dlg;
 dlg.show();
 
 return app.exec();

}


 </source>


A simple model that uses a QStringList as its data source

<source lang="cpp"> /****************************************************************************

    • Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
    • All rights reserved.
    • Contact: Nokia Corporation (qt-info@nokia.com)
    • This file is part of the documentation of the Qt Toolkit.
    • $QT_BEGIN_LICENSE:LGPL$
    • Commercial Usage
    • Licensees holding valid Qt Commercial licenses may use this file in
    • accordance with the Qt Commercial License Agreement provided with the
    • Software or, alternatively, in accordance with the terms contained in
    • a written agreement between you and Nokia.
    • GNU Lesser General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU Lesser
    • General Public License version 2.1 as published by the Free Software
    • Foundation and appearing in the file LICENSE.LGPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU Lesser General Public License version 2.1 requirements
    • will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    • In addition, as a special exception, Nokia gives you certain additional
    • rights. These rights are described in the Nokia Qt LGPL Exception
    • version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
    • GNU General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU
    • General Public License version 3.0 as published by the Free Software
    • Foundation and appearing in the file LICENSE.GPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU General Public License version 3.0 requirements will be
    • met: http://www.gnu.org/copyleft/gpl.html.
    • If you have questions regarding the use of this file, please contact
    • Nokia at qt-info@nokia.com.
    • $QT_END_LICENSE$
                                                                                                                                                        • /

/****************************************************************************

    • Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
    • All rights reserved.
    • Contact: Nokia Corporation (qt-info@nokia.com)
    • This file is part of an example program for Qt.
    • EDITIONS: NOLIMITS
                                                                                                                                                        • /
  1. ifndef MODEL_H
  2. define MODEL_H
  3. include <QAbstractListModel>
  4. include <QObject>
  5. include <QStringList>

class StringListModel : public QAbstractListModel {

   Q_OBJECT

public:

   StringListModel(const QStringList &strings, QObject *parent = 0)
       : QAbstractListModel(parent), stringList(strings) {}
   int rowCount(const QModelIndex &parent = QModelIndex()) const;
   QVariant data(const QModelIndex &index, int role) const;
   QVariant headerData(int section, Qt::Orientation orientation,
                       int role = Qt::DisplayRole) const;
   Qt::ItemFlags flags(const QModelIndex &index) const;
   bool setData(const QModelIndex &index, const QVariant &value,
                int role = Qt::EditRole);
   bool insertRows(int position, int rows, const QModelIndex &index = QModelIndex());
   bool removeRows(int position, int rows, const QModelIndex &index = QModelIndex());

private:

   QStringList stringList;

};

  1. endif


/*

 model.cpp
 A simple model that uses a QStringList as its data source.
  • /
  1. include "model.h"

/*!

   Returns the number of items in the string list as the number of rows
   in the model.
  • /

int StringListModel::rowCount(const QModelIndex &parent) const {

   return stringList.count();

} /*!

   Returns an appropriate value for the requested data.
   If the view requests an invalid index, an invalid variant is returned.
   Any valid index that corresponds to a string in the list causes that
   string to be returned.
  • /

QVariant StringListModel::data(const QModelIndex &index, int role) const {

   if (!index.isValid())
       return QVariant();
   if (index.row() >= stringList.size())
       return QVariant();
   if (role == Qt::DisplayRole)
       return stringList.at(index.row());
   else
       return QVariant();

} /*!

   Returns the appropriate header string depending on the orientation of
   the header and the section. If anything other than the display role is
   requested, we return an invalid variant.
  • /

QVariant StringListModel::headerData(int section, Qt::Orientation orientation,

                                    int role) const

{

   if (role != Qt::DisplayRole)
       return QVariant();
   if (orientation == Qt::Horizontal)
       return QString("Column %1").arg(section);
   else
       return QString("Row %1").arg(section);

} /*!

   Returns an appropriate value for the item"s flags. Valid items are
   enabled, selectable, and editable.
  • /

Qt::ItemFlags StringListModel::flags(const QModelIndex &index) const {

   if (!index.isValid())
       return Qt::ItemIsEnabled;
   return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;

} /*!

   Changes an item in the string list, but only if the following conditions
   are met:
   * The index supplied is valid.
   * The index corresponds to an item to be shown in a view.
   * The role associated with editing text is specified.
   The dataChanged() signal is emitted if the item is changed.
  • /

bool StringListModel::setData(const QModelIndex &index,

                             const QVariant &value, int role)

{

   if (index.isValid() && role == Qt::EditRole) {
       stringList.replace(index.row(), value.toString());
       emit dataChanged(index, index);
       return true;
   }
   return false;

} /*!

   Inserts a number of rows into the model at the specified position.
  • /

bool StringListModel::insertRows(int position, int rows, const QModelIndex &parent) {

   beginInsertRows(QModelIndex(), position, position+rows-1);
   for (int row = 0; row < rows; ++row) {
       stringList.insert(position, "");
   }
   endInsertRows();
   return true;

} /*!

   Removes a number of rows from the model at the specified position.
  • /

bool StringListModel::removeRows(int position, int rows, const QModelIndex &parent) {

   beginRemoveRows(QModelIndex(), position, position+rows-1);
   for (int row = 0; row < rows; ++row) {
       stringList.removeAt(position);
   }
   endRemoveRows();
   return true;

}


  1. ifndef WINDOW_H
  2. define WINDOW_H
  3. include <QMainWindow>
  4. include <QModelIndex>

class QAction; class QListView; class StringListModel; class MainWindow : public QMainWindow {

   Q_OBJECT

public:

   MainWindow();

public slots:

   void insertItem();
   void removeItem();
   void sortAscending();
   void sortDescending();
   void updateMenus(const QModelIndex &current);

private:

   QAction *insertAction;
   QAction *removeAction;
   QListView *listView;
   StringListModel *model;

};

  1. endif


  1. include <QtGui>
  2. include "mainwindow.h"
  3. include "model.h"

MainWindow::MainWindow() {

   QMenu *fileMenu = new QMenu(tr("&File"));
   QAction *quitAction = fileMenu->addAction(tr("E&xit"));
   quitAction->setShortcut(tr("Ctrl+Q"));
   QMenu *itemsMenu = new QMenu(tr("&Items"));
   insertAction = itemsMenu->addAction(tr("&Insert Item"));
   removeAction = itemsMenu->addAction(tr("&Remove Item"));
   QAction *ascendingAction = itemsMenu->addAction(tr("Sort in &Ascending Order"));
   QAction *descendingAction = itemsMenu->addAction(tr("Sort in &Descending Order"));
   menuBar()->addMenu(fileMenu);
   menuBar()->addMenu(itemsMenu);
   QStringList strings;
   strings << tr("Oak") << tr("Fir") << tr("Pine") << tr("Birch")
           << tr("Hazel") << tr("Redwood") << tr("Sycamore") << tr("Chestnut");
   model = new StringListModel(strings, this);

/* For convenient quoting:

   QListView *listView = new QListView(this);
  • /
   listView = new QListView(this);
   listView->setModel(model);
   listView->setSelectionMode(QAbstractItemView::SingleSelection);
   connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
   connect(ascendingAction, SIGNAL(triggered()), this, SLOT(sortAscending()));
   connect(descendingAction, SIGNAL(triggered()), this, SLOT(sortDescending()));
   connect(insertAction, SIGNAL(triggered()), this, SLOT(insertItem()));
   connect(removeAction, SIGNAL(triggered()), this, SLOT(removeItem()));
   connect(listView->selectionModel(),
           SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
           this, SLOT(updateMenus(const QModelIndex &)));
   updateMenus(listView->selectionModel()->currentIndex());
   setCentralWidget(listView);
   setWindowTitle(tr("List View"));

} void MainWindow::sortAscending() {

   model->sort(0, Qt::AscendingOrder);

} void MainWindow::sortDescending() {

   model->sort(0, Qt::DescendingOrder);

} void MainWindow::insertItem() {

   QModelIndex currentIndex = listView->currentIndex();
   if (!currentIndex.isValid())
       return;
   QString itemText = QInputDialog::getText(this, tr("Insert Item"),
       tr("Input text for the new item:"));
   if (itemText.isNull())
       return;
   if (model->insertRow(currentIndex.row(), QModelIndex())) {
       QModelIndex newIndex = model->index(currentIndex.row(), 0, QModelIndex());
       model->setData(newIndex, itemText, Qt::EditRole);
       QString toolTipText = tr("Tooltip:") + itemText;
       QString statusTipText = tr("Status tip:") + itemText;
       QString whatsThisText = tr("What"s This?:") + itemText;
       model->setData(newIndex, toolTipText, Qt::ToolTipRole);
       model->setData(newIndex, toolTipText, Qt::StatusTipRole);
       model->setData(newIndex, whatsThisText, Qt::WhatsThisRole);
   }

} void MainWindow::removeItem() {

   QModelIndex currentIndex = listView->currentIndex();
   if (!currentIndex.isValid())
       return;
   model->removeRow(currentIndex.row(), QModelIndex());

} void MainWindow::updateMenus(const QModelIndex &current) {

   insertAction->setEnabled(current.isValid());
   removeAction->setEnabled(current.isValid());

}


  1. include <QtGui>
  2. include "mainwindow.h"

int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   MainWindow *window = new MainWindow;
   window->show();
   return app.exec();

}


 </source>


Complete demo for QStringList

<source lang="cpp"> /****************************************************************************

    • Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
    • All rights reserved.
    • Contact: Nokia Corporation (qt-info@nokia.com)
    • This file is part of the documentation of the Qt Toolkit.
    • $QT_BEGIN_LICENSE:LGPL$
    • Commercial Usage
    • Licensees holding valid Qt Commercial licenses may use this file in
    • accordance with the Qt Commercial License Agreement provided with the
    • Software or, alternatively, in accordance with the terms contained in
    • a written agreement between you and Nokia.
    • GNU Lesser General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU Lesser
    • General Public License version 2.1 as published by the Free Software
    • Foundation and appearing in the file LICENSE.LGPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU Lesser General Public License version 2.1 requirements
    • will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    • In addition, as a special exception, Nokia gives you certain additional
    • rights. These rights are described in the Nokia Qt LGPL Exception
    • version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
    • GNU General Public License Usage
    • Alternatively, this file may be used under the terms of the GNU
    • General Public License version 3.0 as published by the Free Software
    • Foundation and appearing in the file LICENSE.GPL included in the
    • packaging of this file. Please review the following information to
    • ensure the GNU General Public License version 3.0 requirements will be
    • met: http://www.gnu.org/copyleft/gpl.html.
    • If you have questions regarding the use of this file, please contact
    • Nokia at qt-info@nokia.com.
    • $QT_END_LICENSE$
                                                                                                                                                        • /
  1. include <QtGui>
  2. include <iostream>

using namespace std; class Widget : public QWidget { public:

   Widget(QWidget *parent = 0);

}; Widget::Widget(QWidget *parent)

   : QWidget(parent)

{

   QStringList fonts;
   fonts << "Arial" << "Helvetica" << "Times" << "Courier";
   for (int i = 0; i < fonts.size(); ++i)
        cout << fonts.at(i).toLocal8Bit().constData() << endl;
   QStringListIterator javaStyleIterator(fonts);
   while (javaStyleIterator.hasNext())
        cout << javaStyleIterator.next().toLocal8Bit().constData() << endl;
   QStringList::const_iterator constIterator;
   for (constIterator = fonts.constBegin(); constIterator != fonts.constEnd();
          ++constIterator)
       cout << (*constIterator).toLocal8Bit().constData() << endl;
   QString str = fonts.join(",");
    // str == "Arial,Helvetica,Times,Courier"


   QStringList list;
   list = str.split(",");
    // list: ["Arial", "Helvetica", "Times", "Courier"]
   QStringList monospacedFonts = fonts.filter(QRegExp("Courier|Fixed"));
   QStringList files;
   files << "$QTDIR/src/moc/moc.y"
         << "$QTDIR/src/moc/moc.l"
         << "$QTDIR/include/qconfig.h";
   files.replaceInStrings("$QTDIR", "/usr/lib/qt");
   // files: [ "/usr/lib/qt/src/moc/moc.y", ...]
   QString str1, str2, str3;
   QStringList longerList = (QStringList() << str1 << str2 << str3);
   list.clear();
   list << "Bill Murray" << "John Doe" << "Bill Clinton";
   QStringList result;
   result = list.filter("Bill");
   // result: ["Bill Murray", "Bill Clinton"]
   result.clear();
   foreach (QString str, list) {
       if (str.contains("Bill"))
           result += str;
   }
   list.clear();
   list << "alpha" << "beta" << "gamma" << "epsilon";
   list.replaceInStrings("a", "o");
   // list == ["olpho", "beto", "gommo", "epsilon"]
   list.clear();
   list << "alpha" << "beta" << "gamma" << "epsilon";
   list.replaceInStrings(QRegExp("^a"), "o");
   // list == ["olpha", "beta", "gamma", "epsilon"]
   list.clear();
   list << "Bill Clinton" << "Murray, Bill";
   list.replaceInStrings(QRegExp("^(.*), (.*)$"), "\\2 \\1");
   // list == ["Bill Clinton", "Bill Murray"]

} int main(int argc, char *argv[]) {

   QApplication app(argc, argv);
   Widget widget;
   widget.show();
   return app.exec();

}


 </source>


QStringList demo

<source lang="cpp"> Chapter01\stringlist-stack-queue\special-lists.cpp /*

* Copyright (c) 2006-2007, Johan Thelin
* 
* All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
* 
*     * Redistributions of source code must retain the above copyright notice, 
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice,  
*       this list of conditions and the following disclaimer in the documentation 
*       and/or other materials provided with the distribution.
*     * Neither the name of APress nor the names of its contributors 
*       may be used to endorse or promote products derived from this software 
*       without specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

  1. include <QStringList>
  2. include <QStack>
  3. include <QQueue>
  4. include <QtDebug>

void stringList() {

 QString text;
 
 QStringList list;
 list << "foo" << "bar" << "baz";
 foreach( text, list )
   qDebug() << text;
 
 qDebug() << "---";
 QString all = list.join(",");
 qDebug() << all;
 qDebug() << "---";
 list.replaceInStrings( "a", "oo" );
 foreach( text, list )
   qDebug() << text;      
 
 qDebug() << "---";
 list << all.split(",");
 foreach( text, list )
   qDebug() << text;

} void stackDemo() {

 QStack<QString> stack;
 
 stack.push( "foo" );
 stack.push( "bar" );
 stack.push( "baz" );
 
 QString result;
 while( !stack.isEmpty() )
   result += stack.pop();
 qDebug() << result;

} void queueDemo() {

 QQueue<QString> queue;
 
 queue.enqueue( "foo" );
 queue.enqueue( "bar" );
 queue.enqueue( "baz" );
 
 QString result;
 while( !queue.isEmpty() )
   result += queue.dequeue();
 qDebug() << result;

} int main( void ) {

 qDebug() << "String list";
 stringList();
 
 qDebug() << "Stack";
 stackDemo();
 
 qDebug() << "Queue";
 queueDemo();
 
 return 0;

}


 </source>


Quick sort QStringList

<source lang="cpp">

  1. include <QList>
  2. include <QtAlgorithms> // for qSort()
  3. include <QStringList>
  4. include <QDebug>

class CaseIgnoreString : public QString { public:

   CaseIgnoreString(const QString& other = QString()) : QString(other) {}
   bool operator<(const QString & other) const {
       return toLower() < other.toLower();
   }
   bool operator==(const QString& other) const {
       return toLower() == other.toLower();
   }

}; int main() {

   CaseIgnoreString s1("A"), s2("b"), s3 ("C"), s4("d"), s5 ("D");
   QList<CaseIgnoreString> namelist;
   namelist << s5 << s1 << s3 << s4 << s2;

   qSort(namelist.begin(), namelist.end());
   int i=0;
   foreach (QString stritr, namelist) {
       qDebug() << QString("namelist[%1] = %2").arg(i++).arg(stritr) ;
   }
   QStringList strlist;
   strlist << s5 << s1 << s3 << s4 << s2; 
   qSort(strlist.begin(), strlist.end());
   qDebug() << "StringList sorted: " + strlist.join(", ") << endl;
   return 0;

}


 </source>


Search in a list of fruit names first for the word Pear and then for Orange

<source lang="cpp">

  1. include <QStringList>
  2. include <QDebug>

int main() {

 QStringList list;
 list << "apple" << "pear" << "banana";
 QStringList::iterator i1 = qFind(list.begin(), list.end(), "pear");
 QStringList::iterator i2 = qFind(list.begin(), list.end(), "orange");
 return 0;

}


 </source>


Split QStringList

<source lang="cpp">

  1. include <QStringList>
  2. include <QDebug>

int main() {

   QString winter = "A, B, C";
   QString spring = "D, E, F";
   QString summer = "G, H, I";
   QString fall = "X, Y, Z";
   QStringList list;
   list << winter;        
   list += spring;        
   list.append(summer);   
   list << fall;
   QString allmonths = list.join(", "); 
   QStringList list2 = allmonths.split(", ");  
   Q_ASSERT(list2.size() == 12); 
   foreach (QString str, list) {  
       qDebug() << QString(" [%1] ").arg(str);
   }
   
   return 0;

}


 </source>


STL-Style Iterators

<source lang="cpp">

  1. include <QtCore>
  2. include <QDebug>

using namespace std; int main() {

 QStringList list;
 list << "dog" << "cat" << "mouse";
 QStringList::iterator it;
 for (it = list.begin(); it != list.end(); ++it)
 {
   qDebug() << *it << endl;
 }
 return 0;

}


 </source>


using QStringList, append to and output and join

<source lang="cpp">

  1. include <QStringList>
  2. include <QDebug>

int main() {

   QString winter = "A, B, C";
   QString spring = "D, E, F";
   QString summer = "G, H, I";
   QString fall = "X, Y, Z";
   QStringList list;
   list << winter;        
   list += spring;        
   list.append(summer);   
   list << fall;
   qDebug() << "The Spring months are: " << list[1] ;
   
   
   QString allmonths = list.join(", "); 
   qDebug() << allmonths;
   return 0;

}


 </source>