From 806dda08d685bc5f9ed71dfe8b61f21848d48066 Mon Sep 17 00:00:00 2001 From: Gabriel de Dietrich Date: Fri, 17 Aug 2012 13:23:19 +0200 Subject: Moving .qdoc files under examples/widgets/doc Updated those .qdoc files to refer to the new relative examples emplacement. Images and snippets to be moved later. Also grouped all widgets related examples under widgets. Change-Id: Ib29696e2d8948524537f53e8dda88f9ee26a597f Reviewed-by: J-P Nurmi --- examples/widgets/itemviews/README | 8 + .../widgets/itemviews/addressbook/adddialog.cpp | 82 +++ examples/widgets/itemviews/addressbook/adddialog.h | 71 +++ .../itemviews/addressbook/addressbook.desktop | 11 + .../widgets/itemviews/addressbook/addressbook.pro | 19 + .../itemviews/addressbook/addresswidget.cpp | 236 ++++++++ .../widgets/itemviews/addressbook/addresswidget.h | 82 +++ examples/widgets/itemviews/addressbook/main.cpp | 52 ++ .../widgets/itemviews/addressbook/mainwindow.cpp | 137 +++++ .../widgets/itemviews/addressbook/mainwindow.h | 75 +++ .../itemviews/addressbook/newaddresstab.cpp | 77 +++ .../widgets/itemviews/addressbook/newaddresstab.h | 74 +++ .../widgets/itemviews/addressbook/tablemodel.cpp | 184 ++++++ .../widgets/itemviews/addressbook/tablemodel.h | 72 +++ .../basicsortfiltermodel.desktop | 11 + .../basicsortfiltermodel/basicsortfiltermodel.pro | 12 + .../itemviews/basicsortfiltermodel/main.cpp | 93 +++ .../itemviews/basicsortfiltermodel/window.cpp | 157 +++++ .../itemviews/basicsortfiltermodel/window.h | 88 +++ examples/widgets/itemviews/chart/chart.desktop | 11 + examples/widgets/itemviews/chart/chart.pro | 18 + examples/widgets/itemviews/chart/chart.qrc | 5 + examples/widgets/itemviews/chart/main.cpp | 53 ++ examples/widgets/itemviews/chart/mainwindow.cpp | 172 ++++++ examples/widgets/itemviews/chart/mainwindow.h | 72 +++ examples/widgets/itemviews/chart/mydata.cht | 8 + examples/widgets/itemviews/chart/pieview.cpp | 557 ++++++++++++++++++ examples/widgets/itemviews/chart/pieview.h | 114 ++++ examples/widgets/itemviews/chart/qtdata.cht | 14 + .../coloreditorfactory/coloreditorfactory.desktop | 11 + .../coloreditorfactory/coloreditorfactory.pro | 14 + .../coloreditorfactory/colorlisteditor.cpp | 76 +++ .../itemviews/coloreditorfactory/colorlisteditor.h | 69 +++ .../widgets/itemviews/coloreditorfactory/main.cpp | 53 ++ .../itemviews/coloreditorfactory/window.cpp | 94 +++ .../widgets/itemviews/coloreditorfactory/window.h | 57 ++ .../combowidgetmapper/combowidgetmapper.desktop | 11 + .../combowidgetmapper/combowidgetmapper.pro | 11 + .../widgets/itemviews/combowidgetmapper/main.cpp | 51 ++ .../widgets/itemviews/combowidgetmapper/window.cpp | 136 +++++ .../widgets/itemviews/combowidgetmapper/window.h | 86 +++ .../customsortfiltermodel.desktop | 11 + .../customsortfiltermodel.pro | 14 + .../itemviews/customsortfiltermodel/main.cpp | 95 +++ .../mysortfilterproxymodel.cpp | 115 ++++ .../customsortfiltermodel/mysortfilterproxymodel.h | 73 +++ .../itemviews/customsortfiltermodel/window.cpp | 166 ++++++ .../itemviews/customsortfiltermodel/window.h | 90 +++ examples/widgets/itemviews/dirview/dirview.desktop | 11 + examples/widgets/itemviews/dirview/dirview.pro | 9 + examples/widgets/itemviews/dirview/main.cpp | 62 ++ .../itemviews/editabletreemodel/default.txt | 40 ++ .../editabletreemodel/editabletreemodel.desktop | 11 + .../editabletreemodel/editabletreemodel.pro | 18 + .../editabletreemodel/editabletreemodel.qrc | 5 + .../widgets/itemviews/editabletreemodel/main.cpp | 53 ++ .../itemviews/editabletreemodel/mainwindow.cpp | 181 ++++++ .../itemviews/editabletreemodel/mainwindow.h | 71 +++ .../itemviews/editabletreemodel/mainwindow.ui | 128 +++++ .../itemviews/editabletreemodel/treeitem.cpp | 179 ++++++ .../widgets/itemviews/editabletreemodel/treeitem.h | 74 +++ .../itemviews/editabletreemodel/treemodel.cpp | 288 ++++++++++ .../itemviews/editabletreemodel/treemodel.h | 97 ++++ .../widgets/itemviews/fetchmore/fetchmore.desktop | 11 + examples/widgets/itemviews/fetchmore/fetchmore.pro | 13 + .../widgets/itemviews/fetchmore/filelistmodel.cpp | 116 ++++ .../widgets/itemviews/fetchmore/filelistmodel.h | 75 +++ examples/widgets/itemviews/fetchmore/main.cpp | 50 ++ examples/widgets/itemviews/fetchmore/window.cpp | 81 +++ examples/widgets/itemviews/fetchmore/window.h | 64 +++ .../itemviews/frozencolumn/freezetablewidget.cpp | 165 ++++++ .../itemviews/frozencolumn/freezetablewidget.h | 72 +++ .../itemviews/frozencolumn/frozencolumn.desktop | 11 + .../itemviews/frozencolumn/frozencolumn.pro | 11 + examples/widgets/itemviews/frozencolumn/grades.qrc | 5 + examples/widgets/itemviews/frozencolumn/grades.txt | 36 ++ examples/widgets/itemviews/frozencolumn/main.cpp | 88 +++ examples/widgets/itemviews/interview/README | 2 + .../widgets/itemviews/interview/images/folder.png | Bin 0 -> 3910 bytes .../itemviews/interview/images/interview.png | Bin 0 -> 174 bytes .../itemviews/interview/images/services.png | Bin 0 -> 3749 bytes examples/widgets/itemviews/interview/interview.pro | 19 + examples/widgets/itemviews/interview/interview.qrc | 7 + examples/widgets/itemviews/interview/main.cpp | 95 +++ examples/widgets/itemviews/interview/model.cpp | 147 +++++ examples/widgets/itemviews/interview/model.h | 90 +++ examples/widgets/itemviews/itemviews.pro | 25 + .../widgets/itemviews/pixelator/imagemodel.cpp | 92 +++ examples/widgets/itemviews/pixelator/imagemodel.h | 68 +++ examples/widgets/itemviews/pixelator/images.qrc | 5 + examples/widgets/itemviews/pixelator/images/qt.png | Bin 0 -> 656 bytes examples/widgets/itemviews/pixelator/main.cpp | 54 ++ .../widgets/itemviews/pixelator/mainwindow.cpp | 248 ++++++++ examples/widgets/itemviews/pixelator/mainwindow.h | 74 +++ .../widgets/itemviews/pixelator/pixelator.desktop | 11 + examples/widgets/itemviews/pixelator/pixelator.pro | 17 + .../widgets/itemviews/pixelator/pixeldelegate.cpp | 107 ++++ .../widgets/itemviews/pixelator/pixeldelegate.h | 79 +++ examples/widgets/itemviews/puzzle/example.jpg | Bin 0 -> 42654 bytes examples/widgets/itemviews/puzzle/main.cpp | 54 ++ examples/widgets/itemviews/puzzle/mainwindow.cpp | 149 +++++ examples/widgets/itemviews/puzzle/mainwindow.h | 77 +++ examples/widgets/itemviews/puzzle/piecesmodel.cpp | 203 +++++++ examples/widgets/itemviews/puzzle/piecesmodel.h | 82 +++ examples/widgets/itemviews/puzzle/puzzle.desktop | 11 + examples/widgets/itemviews/puzzle/puzzle.pro | 22 + examples/widgets/itemviews/puzzle/puzzle.qrc | 5 + examples/widgets/itemviews/puzzle/puzzlewidget.cpp | 214 +++++++ examples/widgets/itemviews/puzzle/puzzlewidget.h | 89 +++ .../widgets/itemviews/simpledommodel/domitem.cpp | 101 ++++ .../widgets/itemviews/simpledommodel/domitem.h | 66 +++ .../widgets/itemviews/simpledommodel/dommodel.cpp | 189 ++++++ .../widgets/itemviews/simpledommodel/dommodel.h | 76 +++ examples/widgets/itemviews/simpledommodel/main.cpp | 52 ++ .../itemviews/simpledommodel/mainwindow.cpp | 84 +++ .../widgets/itemviews/simpledommodel/mainwindow.h | 70 +++ .../simpledommodel/simpledommodel.desktop | 11 + .../itemviews/simpledommodel/simpledommodel.pro | 16 + .../widgets/itemviews/simpletreemodel/default.txt | 40 ++ .../widgets/itemviews/simpletreemodel/main.cpp | 61 ++ .../simpletreemodel/simpletreemodel.desktop | 11 + .../itemviews/simpletreemodel/simpletreemodel.pro | 15 + .../itemviews/simpletreemodel/simpletreemodel.qrc | 5 + .../widgets/itemviews/simpletreemodel/treeitem.cpp | 116 ++++ .../widgets/itemviews/simpletreemodel/treeitem.h | 70 +++ .../itemviews/simpletreemodel/treemodel.cpp | 218 +++++++ .../widgets/itemviews/simpletreemodel/treemodel.h | 76 +++ .../widgets/itemviews/simplewidgetmapper/main.cpp | 51 ++ .../simplewidgetmapper/simplewidgetmapper.desktop | 11 + .../simplewidgetmapper/simplewidgetmapper.pro | 11 + .../itemviews/simplewidgetmapper/window.cpp | 133 +++++ .../widgets/itemviews/simplewidgetmapper/window.h | 84 +++ .../widgets/itemviews/spinboxdelegate/delegate.cpp | 102 ++++ .../widgets/itemviews/spinboxdelegate/delegate.h | 70 +++ .../widgets/itemviews/spinboxdelegate/main.cpp | 86 +++ .../spinboxdelegate/spinboxdelegate.desktop | 11 + .../itemviews/spinboxdelegate/spinboxdelegate.pro | 13 + .../itemviews/spreadsheet/images/interview.png | Bin 0 -> 174 bytes examples/widgets/itemviews/spreadsheet/main.cpp | 55 ++ .../widgets/itemviews/spreadsheet/printview.cpp | 62 ++ examples/widgets/itemviews/spreadsheet/printview.h | 63 ++ .../widgets/itemviews/spreadsheet/spreadsheet.cpp | 639 +++++++++++++++++++++ .../widgets/itemviews/spreadsheet/spreadsheet.h | 124 ++++ .../widgets/itemviews/spreadsheet/spreadsheet.pro | 23 + .../widgets/itemviews/spreadsheet/spreadsheet.qrc | 5 + .../itemviews/spreadsheet/spreadsheetdelegate.cpp | 114 ++++ .../itemviews/spreadsheet/spreadsheetdelegate.h | 65 +++ .../itemviews/spreadsheet/spreadsheetitem.cpp | 167 ++++++ .../itemviews/spreadsheet/spreadsheetitem.h | 73 +++ examples/widgets/itemviews/stardelegate/main.cpp | 107 ++++ .../itemviews/stardelegate/stardelegate.cpp | 129 +++++ .../itemviews/stardelegate/stardelegate.desktop | 11 + .../widgets/itemviews/stardelegate/stardelegate.h | 69 +++ .../itemviews/stardelegate/stardelegate.pro | 17 + .../widgets/itemviews/stardelegate/stareditor.cpp | 98 ++++ .../widgets/itemviews/stardelegate/stareditor.h | 77 +++ .../widgets/itemviews/stardelegate/starrating.cpp | 102 ++++ .../widgets/itemviews/stardelegate/starrating.h | 76 +++ 158 files changed, 11794 insertions(+) create mode 100644 examples/widgets/itemviews/README create mode 100644 examples/widgets/itemviews/addressbook/adddialog.cpp create mode 100644 examples/widgets/itemviews/addressbook/adddialog.h create mode 100644 examples/widgets/itemviews/addressbook/addressbook.desktop create mode 100644 examples/widgets/itemviews/addressbook/addressbook.pro create mode 100644 examples/widgets/itemviews/addressbook/addresswidget.cpp create mode 100644 examples/widgets/itemviews/addressbook/addresswidget.h create mode 100644 examples/widgets/itemviews/addressbook/main.cpp create mode 100644 examples/widgets/itemviews/addressbook/mainwindow.cpp create mode 100644 examples/widgets/itemviews/addressbook/mainwindow.h create mode 100644 examples/widgets/itemviews/addressbook/newaddresstab.cpp create mode 100644 examples/widgets/itemviews/addressbook/newaddresstab.h create mode 100644 examples/widgets/itemviews/addressbook/tablemodel.cpp create mode 100644 examples/widgets/itemviews/addressbook/tablemodel.h create mode 100644 examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.desktop create mode 100644 examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.pro create mode 100644 examples/widgets/itemviews/basicsortfiltermodel/main.cpp create mode 100644 examples/widgets/itemviews/basicsortfiltermodel/window.cpp create mode 100644 examples/widgets/itemviews/basicsortfiltermodel/window.h create mode 100644 examples/widgets/itemviews/chart/chart.desktop create mode 100644 examples/widgets/itemviews/chart/chart.pro create mode 100644 examples/widgets/itemviews/chart/chart.qrc create mode 100644 examples/widgets/itemviews/chart/main.cpp create mode 100644 examples/widgets/itemviews/chart/mainwindow.cpp create mode 100644 examples/widgets/itemviews/chart/mainwindow.h create mode 100644 examples/widgets/itemviews/chart/mydata.cht create mode 100644 examples/widgets/itemviews/chart/pieview.cpp create mode 100644 examples/widgets/itemviews/chart/pieview.h create mode 100644 examples/widgets/itemviews/chart/qtdata.cht create mode 100644 examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.desktop create mode 100644 examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.pro create mode 100644 examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp create mode 100644 examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h create mode 100644 examples/widgets/itemviews/coloreditorfactory/main.cpp create mode 100644 examples/widgets/itemviews/coloreditorfactory/window.cpp create mode 100644 examples/widgets/itemviews/coloreditorfactory/window.h create mode 100644 examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.desktop create mode 100644 examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.pro create mode 100644 examples/widgets/itemviews/combowidgetmapper/main.cpp create mode 100644 examples/widgets/itemviews/combowidgetmapper/window.cpp create mode 100644 examples/widgets/itemviews/combowidgetmapper/window.h create mode 100644 examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.desktop create mode 100644 examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.pro create mode 100644 examples/widgets/itemviews/customsortfiltermodel/main.cpp create mode 100644 examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp create mode 100644 examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.h create mode 100644 examples/widgets/itemviews/customsortfiltermodel/window.cpp create mode 100644 examples/widgets/itemviews/customsortfiltermodel/window.h create mode 100644 examples/widgets/itemviews/dirview/dirview.desktop create mode 100644 examples/widgets/itemviews/dirview/dirview.pro create mode 100644 examples/widgets/itemviews/dirview/main.cpp create mode 100644 examples/widgets/itemviews/editabletreemodel/default.txt create mode 100644 examples/widgets/itemviews/editabletreemodel/editabletreemodel.desktop create mode 100644 examples/widgets/itemviews/editabletreemodel/editabletreemodel.pro create mode 100644 examples/widgets/itemviews/editabletreemodel/editabletreemodel.qrc create mode 100644 examples/widgets/itemviews/editabletreemodel/main.cpp create mode 100644 examples/widgets/itemviews/editabletreemodel/mainwindow.cpp create mode 100644 examples/widgets/itemviews/editabletreemodel/mainwindow.h create mode 100644 examples/widgets/itemviews/editabletreemodel/mainwindow.ui create mode 100644 examples/widgets/itemviews/editabletreemodel/treeitem.cpp create mode 100644 examples/widgets/itemviews/editabletreemodel/treeitem.h create mode 100644 examples/widgets/itemviews/editabletreemodel/treemodel.cpp create mode 100644 examples/widgets/itemviews/editabletreemodel/treemodel.h create mode 100644 examples/widgets/itemviews/fetchmore/fetchmore.desktop create mode 100644 examples/widgets/itemviews/fetchmore/fetchmore.pro create mode 100644 examples/widgets/itemviews/fetchmore/filelistmodel.cpp create mode 100644 examples/widgets/itemviews/fetchmore/filelistmodel.h create mode 100644 examples/widgets/itemviews/fetchmore/main.cpp create mode 100644 examples/widgets/itemviews/fetchmore/window.cpp create mode 100644 examples/widgets/itemviews/fetchmore/window.h create mode 100644 examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp create mode 100644 examples/widgets/itemviews/frozencolumn/freezetablewidget.h create mode 100644 examples/widgets/itemviews/frozencolumn/frozencolumn.desktop create mode 100644 examples/widgets/itemviews/frozencolumn/frozencolumn.pro create mode 100644 examples/widgets/itemviews/frozencolumn/grades.qrc create mode 100644 examples/widgets/itemviews/frozencolumn/grades.txt create mode 100644 examples/widgets/itemviews/frozencolumn/main.cpp create mode 100644 examples/widgets/itemviews/interview/README create mode 100644 examples/widgets/itemviews/interview/images/folder.png create mode 100644 examples/widgets/itemviews/interview/images/interview.png create mode 100644 examples/widgets/itemviews/interview/images/services.png create mode 100644 examples/widgets/itemviews/interview/interview.pro create mode 100644 examples/widgets/itemviews/interview/interview.qrc create mode 100644 examples/widgets/itemviews/interview/main.cpp create mode 100644 examples/widgets/itemviews/interview/model.cpp create mode 100644 examples/widgets/itemviews/interview/model.h create mode 100644 examples/widgets/itemviews/itemviews.pro create mode 100644 examples/widgets/itemviews/pixelator/imagemodel.cpp create mode 100644 examples/widgets/itemviews/pixelator/imagemodel.h create mode 100644 examples/widgets/itemviews/pixelator/images.qrc create mode 100644 examples/widgets/itemviews/pixelator/images/qt.png create mode 100644 examples/widgets/itemviews/pixelator/main.cpp create mode 100644 examples/widgets/itemviews/pixelator/mainwindow.cpp create mode 100644 examples/widgets/itemviews/pixelator/mainwindow.h create mode 100644 examples/widgets/itemviews/pixelator/pixelator.desktop create mode 100644 examples/widgets/itemviews/pixelator/pixelator.pro create mode 100644 examples/widgets/itemviews/pixelator/pixeldelegate.cpp create mode 100644 examples/widgets/itemviews/pixelator/pixeldelegate.h create mode 100644 examples/widgets/itemviews/puzzle/example.jpg create mode 100644 examples/widgets/itemviews/puzzle/main.cpp create mode 100644 examples/widgets/itemviews/puzzle/mainwindow.cpp create mode 100644 examples/widgets/itemviews/puzzle/mainwindow.h create mode 100644 examples/widgets/itemviews/puzzle/piecesmodel.cpp create mode 100644 examples/widgets/itemviews/puzzle/piecesmodel.h create mode 100644 examples/widgets/itemviews/puzzle/puzzle.desktop create mode 100644 examples/widgets/itemviews/puzzle/puzzle.pro create mode 100644 examples/widgets/itemviews/puzzle/puzzle.qrc create mode 100644 examples/widgets/itemviews/puzzle/puzzlewidget.cpp create mode 100644 examples/widgets/itemviews/puzzle/puzzlewidget.h create mode 100644 examples/widgets/itemviews/simpledommodel/domitem.cpp create mode 100644 examples/widgets/itemviews/simpledommodel/domitem.h create mode 100644 examples/widgets/itemviews/simpledommodel/dommodel.cpp create mode 100644 examples/widgets/itemviews/simpledommodel/dommodel.h create mode 100644 examples/widgets/itemviews/simpledommodel/main.cpp create mode 100644 examples/widgets/itemviews/simpledommodel/mainwindow.cpp create mode 100644 examples/widgets/itemviews/simpledommodel/mainwindow.h create mode 100644 examples/widgets/itemviews/simpledommodel/simpledommodel.desktop create mode 100644 examples/widgets/itemviews/simpledommodel/simpledommodel.pro create mode 100644 examples/widgets/itemviews/simpletreemodel/default.txt create mode 100644 examples/widgets/itemviews/simpletreemodel/main.cpp create mode 100644 examples/widgets/itemviews/simpletreemodel/simpletreemodel.desktop create mode 100644 examples/widgets/itemviews/simpletreemodel/simpletreemodel.pro create mode 100644 examples/widgets/itemviews/simpletreemodel/simpletreemodel.qrc create mode 100644 examples/widgets/itemviews/simpletreemodel/treeitem.cpp create mode 100644 examples/widgets/itemviews/simpletreemodel/treeitem.h create mode 100644 examples/widgets/itemviews/simpletreemodel/treemodel.cpp create mode 100644 examples/widgets/itemviews/simpletreemodel/treemodel.h create mode 100644 examples/widgets/itemviews/simplewidgetmapper/main.cpp create mode 100644 examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.desktop create mode 100644 examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.pro create mode 100644 examples/widgets/itemviews/simplewidgetmapper/window.cpp create mode 100644 examples/widgets/itemviews/simplewidgetmapper/window.h create mode 100644 examples/widgets/itemviews/spinboxdelegate/delegate.cpp create mode 100644 examples/widgets/itemviews/spinboxdelegate/delegate.h create mode 100644 examples/widgets/itemviews/spinboxdelegate/main.cpp create mode 100644 examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.desktop create mode 100644 examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.pro create mode 100644 examples/widgets/itemviews/spreadsheet/images/interview.png create mode 100644 examples/widgets/itemviews/spreadsheet/main.cpp create mode 100644 examples/widgets/itemviews/spreadsheet/printview.cpp create mode 100644 examples/widgets/itemviews/spreadsheet/printview.h create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheet.cpp create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheet.h create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheet.pro create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheet.qrc create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp create mode 100644 examples/widgets/itemviews/spreadsheet/spreadsheetitem.h create mode 100644 examples/widgets/itemviews/stardelegate/main.cpp create mode 100644 examples/widgets/itemviews/stardelegate/stardelegate.cpp create mode 100644 examples/widgets/itemviews/stardelegate/stardelegate.desktop create mode 100644 examples/widgets/itemviews/stardelegate/stardelegate.h create mode 100644 examples/widgets/itemviews/stardelegate/stardelegate.pro create mode 100644 examples/widgets/itemviews/stardelegate/stareditor.cpp create mode 100644 examples/widgets/itemviews/stardelegate/stareditor.h create mode 100644 examples/widgets/itemviews/stardelegate/starrating.cpp create mode 100644 examples/widgets/itemviews/stardelegate/starrating.h (limited to 'examples/widgets/itemviews') diff --git a/examples/widgets/itemviews/README b/examples/widgets/itemviews/README new file mode 100644 index 0000000000..bded96a849 --- /dev/null +++ b/examples/widgets/itemviews/README @@ -0,0 +1,8 @@ +Item views are widgets that typically display data sets. Qt 4's model/view +framework lets you handle large data sets by separating the underlying data +from the way it is represented to the user, and provides support for +customized rendering through the use of delegates. + + +Documentation for these examples can be found via the Examples +link in the main Qt documentation. diff --git a/examples/widgets/itemviews/addressbook/adddialog.cpp b/examples/widgets/itemviews/addressbook/adddialog.cpp new file mode 100644 index 0000000000..f34bd0d46e --- /dev/null +++ b/examples/widgets/itemviews/addressbook/adddialog.cpp @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "adddialog.h" + +//! [0] +AddDialog::AddDialog(QWidget *parent) + : QDialog(parent) +{ + nameLabel = new QLabel("Name"); + addressLabel = new QLabel("Address"); + okButton = new QPushButton("OK"); + cancelButton = new QPushButton("Cancel"); + + nameText = new QLineEdit; + addressText = new QTextEdit; + + QGridLayout *gLayout = new QGridLayout; + gLayout->setColumnStretch(1, 2); + gLayout->addWidget(nameLabel, 0, 0); + gLayout->addWidget(nameText, 0, 1); + + gLayout->addWidget(addressLabel, 1, 0, Qt::AlignLeft|Qt::AlignTop); + gLayout->addWidget(addressText, 1, 1, Qt::AlignLeft); + + QHBoxLayout *buttonLayout = new QHBoxLayout; + buttonLayout->addWidget(okButton); + buttonLayout->addWidget(cancelButton); + + gLayout->addLayout(buttonLayout, 2, 1, Qt::AlignRight); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(gLayout); + setLayout(mainLayout); + + connect(okButton, SIGNAL(clicked()), + this, SLOT(accept())); + + connect(cancelButton, SIGNAL(clicked()), + this, SLOT(reject())); + + setWindowTitle(tr("Add a Contact")); +} +//! [0] diff --git a/examples/widgets/itemviews/addressbook/adddialog.h b/examples/widgets/itemviews/addressbook/adddialog.h new file mode 100644 index 0000000000..6d9093b638 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/adddialog.h @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ADDDIALOG_H +#define ADDDIALOG_H + +#include + +QT_BEGIN_NAMESPACE +class QLabel; +class QPushButton; +class QTextEdit; +class QLineEdit; +QT_END_NAMESPACE + +//! [0] +class AddDialog : public QDialog +{ + Q_OBJECT + +public: + AddDialog(QWidget *parent=0); + QLineEdit *nameText; + QTextEdit *addressText; + +private: + QLabel *nameLabel; + QLabel *addressLabel; + QPushButton *okButton; + QPushButton *cancelButton; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/addressbook/addressbook.desktop b/examples/widgets/itemviews/addressbook/addressbook.desktop new file mode 100644 index 0000000000..11767f59d8 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/addressbook.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Address Book +Exec=/opt/usr/bin/addressbook +Icon=addressbook +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/addressbook/addressbook.pro b/examples/widgets/itemviews/addressbook/addressbook.pro new file mode 100644 index 0000000000..32cbc4ca36 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/addressbook.pro @@ -0,0 +1,19 @@ +SOURCES = adddialog.cpp \ + addresswidget.cpp \ + main.cpp \ + mainwindow.cpp \ + newaddresstab.cpp \ + tablemodel.cpp +HEADERS = adddialog.h \ + addresswidget.h \ + mainwindow.h \ + newaddresstab.h \ + tablemodel.h + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/addressbook +sources.files = $$SOURCES $$HEADERS $$RESOURCES addressbook.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/addressbook +INSTALLS += target sources +QT += widgets + diff --git a/examples/widgets/itemviews/addressbook/addresswidget.cpp b/examples/widgets/itemviews/addressbook/addresswidget.cpp new file mode 100644 index 0000000000..066d5588c7 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/addresswidget.cpp @@ -0,0 +1,236 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "addresswidget.h" +#include "adddialog.h" + +//! [0] +AddressWidget::AddressWidget(QWidget *parent) + : QTabWidget(parent) +{ + table = new TableModel(this); + newAddressTab = new NewAddressTab(this); + connect(newAddressTab, SIGNAL(sendDetails(QString,QString)), + this, SLOT(addEntry(QString,QString))); + + addTab(newAddressTab, "Address Book"); + + setupTabs(); +} +//! [0] + +//! [2] +void AddressWidget::addEntry() +{ + AddDialog aDialog; + + if (aDialog.exec()) { + QString name = aDialog.nameText->text(); + QString address = aDialog.addressText->toPlainText(); + + addEntry(name, address); + } +} +//! [2] + +//! [3] +void AddressWidget::addEntry(QString name, QString address) +{ + QList< QPair >list = table->getList(); + QPair pair(name, address); + + if (!list.contains(pair)) { + table->insertRows(0, 1, QModelIndex()); + + QModelIndex index = table->index(0, 0, QModelIndex()); + table->setData(index, name, Qt::EditRole); + index = table->index(0, 1, QModelIndex()); + table->setData(index, address, Qt::EditRole); + removeTab(indexOf(newAddressTab)); + } else { + QMessageBox::information(this, tr("Duplicate Name"), + tr("The name \"%1\" already exists.").arg(name)); + } +} +//! [3] + +//! [4a] +void AddressWidget::editEntry() +{ + QTableView *temp = static_cast(currentWidget()); + QSortFilterProxyModel *proxy = static_cast(temp->model()); + QItemSelectionModel *selectionModel = temp->selectionModel(); + + QModelIndexList indexes = selectionModel->selectedRows(); + QModelIndex index, i; + QString name; + QString address; + int row = -1; + + foreach (index, indexes) { + row = proxy->mapToSource(index).row(); + i = table->index(row, 0, QModelIndex()); + QVariant varName = table->data(i, Qt::DisplayRole); + name = varName.toString(); + + i = table->index(row, 1, QModelIndex()); + QVariant varAddr = table->data(i, Qt::DisplayRole); + address = varAddr.toString(); + } +//! [4a] + +//! [4b] + AddDialog aDialog; + aDialog.setWindowTitle(tr("Edit a Contact")); + + aDialog.nameText->setReadOnly(true); + aDialog.nameText->setText(name); + aDialog.addressText->setText(address); + + if (aDialog.exec()) { + QString newAddress = aDialog.addressText->toPlainText(); + if (newAddress != address) { + i = table->index(row, 1, QModelIndex()); + table->setData(i, newAddress, Qt::EditRole); + } + } +} +//! [4b] + +//! [5] +void AddressWidget::removeEntry() +{ + QTableView *temp = static_cast(currentWidget()); + QSortFilterProxyModel *proxy = static_cast(temp->model()); + QItemSelectionModel *selectionModel = temp->selectionModel(); + + QModelIndexList indexes = selectionModel->selectedRows(); + QModelIndex index; + + foreach (index, indexes) { + int row = proxy->mapToSource(index).row(); + table->removeRows(row, 1, QModelIndex()); + } + + if (table->rowCount(QModelIndex()) == 0) { + insertTab(0, newAddressTab, "Address Book"); + } +} +//! [5] + +//! [1] +void AddressWidget::setupTabs() +{ + QStringList groups; + groups << "ABC" << "DEF" << "GHI" << "JKL" << "MNO" << "PQR" << "STU" << "VW" << "XYZ"; + + for (int i = 0; i < groups.size(); ++i) { + QString str = groups.at(i); + + proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(table); + + QTableView *tableView = new QTableView; + tableView->setModel(proxyModel); + tableView->setSortingEnabled(true); + tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + tableView->horizontalHeader()->setStretchLastSection(true); + tableView->verticalHeader()->hide(); + tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); + tableView->setSelectionMode(QAbstractItemView::SingleSelection); + + QString newStr = QString("^[%1].*").arg(str); + + proxyModel->setFilterRegExp(QRegExp(newStr, Qt::CaseInsensitive)); + proxyModel->setFilterKeyColumn(0); + proxyModel->sort(0, Qt::AscendingOrder); + + connect(tableView->selectionModel(), + SIGNAL(selectionChanged(QItemSelection,QItemSelection)), + this, SIGNAL(selectionChanged(QItemSelection))); + + addTab(tableView, str); + } +} +//! [1] + +//! [7] +void AddressWidget::readFromFile(QString fileName) +{ + QFile file(fileName); + + if (!file.open(QIODevice::ReadOnly)) { + QMessageBox::information(this, tr("Unable to open file"), + file.errorString()); + return; + } + + QList< QPair > pairs = table->getList(); + QDataStream in(&file); + in >> pairs; + + if (pairs.isEmpty()) { + QMessageBox::information(this, tr("No contacts in file"), + tr("The file you are attempting to open contains no contacts.")); + } else { + for (int i=0; i p = pairs.at(i); + addEntry(p.first, p.second); + } + } +} +//! [7] + +//! [6] +void AddressWidget::writeToFile(QString fileName) +{ + QFile file(fileName); + + if (!file.open(QIODevice::WriteOnly)) { + QMessageBox::information(this, tr("Unable to open file"), file.errorString()); + return; + } + + QList< QPair > pairs = table->getList(); + QDataStream out(&file); + out << pairs; +} +//! [6] diff --git a/examples/widgets/itemviews/addressbook/addresswidget.h b/examples/widgets/itemviews/addressbook/addresswidget.h new file mode 100644 index 0000000000..3a46818463 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/addresswidget.h @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ADDRESSWIDGET_H +#define ADDRESSWIDGET_H + +#include +#include +#include "tablemodel.h" +#include "newaddresstab.h" + +QT_BEGIN_NAMESPACE +class QSortFilterProxyModel; +class QItemSelectionModel; +QT_END_NAMESPACE + +//! [0] +class AddressWidget : public QTabWidget +{ + Q_OBJECT + +public: + AddressWidget(QWidget *parent=0); + void readFromFile(QString fileName); + void writeToFile(QString fileName); + +public slots: + void addEntry(); + void addEntry(QString name, QString address); + void editEntry(); + void removeEntry(); + +signals: + void selectionChanged (const QItemSelection &selected); + +private: + void setupTabs(); + + TableModel *table; + NewAddressTab *newAddressTab; + QSortFilterProxyModel *proxyModel; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/addressbook/main.cpp b/examples/widgets/itemviews/addressbook/main.cpp new file mode 100644 index 0000000000..9f388dc123 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/main.cpp @@ -0,0 +1,52 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mainwindow.h" + +//! [0] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + MainWindow mw; + mw.show(); + return app.exec(); +} +//! [0] diff --git a/examples/widgets/itemviews/addressbook/mainwindow.cpp b/examples/widgets/itemviews/addressbook/mainwindow.cpp new file mode 100644 index 0000000000..e16aec94b0 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/mainwindow.cpp @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mainwindow.h" + +//! [0] +MainWindow::MainWindow() +{ + addressWidget = new AddressWidget; + setCentralWidget(addressWidget); + createMenus(); + setWindowTitle(tr("Address Book")); +} +//! [0] + +//! [1a] +void MainWindow::createMenus() +{ + fileMenu = menuBar()->addMenu(tr("&File")); + + openAct = new QAction(tr("&Open..."), this); + fileMenu->addAction(openAct); + connect(openAct, SIGNAL(triggered()), + this, SLOT(openFile())); +//! [1a] + + saveAct = new QAction(tr("&Save As..."), this); + fileMenu->addAction(saveAct); + connect(saveAct, SIGNAL(triggered()), + this, SLOT(saveFile())); + + fileMenu->addSeparator(); + + exitAct = new QAction(tr("E&xit"), this); + fileMenu->addAction(exitAct); + connect(exitAct, SIGNAL(triggered()), + this, SLOT(close())); + + toolMenu = menuBar()->addMenu(tr("&Tools")); + + addAct = new QAction(tr("&Add Entry..."), this); + toolMenu->addAction(addAct); + connect(addAct, SIGNAL(triggered()), + addressWidget, SLOT(addEntry())); + +//! [1b] + editAct = new QAction(tr("&Edit Entry..."), this); + editAct->setEnabled(false); + toolMenu->addAction(editAct); + connect(editAct, SIGNAL(triggered()), + addressWidget, SLOT(editEntry())); + + toolMenu->addSeparator(); + + removeAct = new QAction(tr("&Remove Entry"), this); + removeAct->setEnabled(false); + toolMenu->addAction(removeAct); + connect(removeAct, SIGNAL(triggered()), + addressWidget, SLOT(removeEntry())); + + connect(addressWidget, SIGNAL(selectionChanged(QItemSelection)), + this, SLOT(updateActions(QItemSelection))); +} +//! [1b] + +//! [2] +void MainWindow::openFile() +{ + QString fileName = QFileDialog::getOpenFileName(this); + if (!fileName.isEmpty()) { + addressWidget->readFromFile(fileName); + } +} +//! [2] + +//! [3] +void MainWindow::saveFile() +{ + QString fileName = QFileDialog::getSaveFileName(this); + if (!fileName.isEmpty()) { + addressWidget->writeToFile(fileName); + } +} +//! [3] + +//! [4] +void MainWindow::updateActions(const QItemSelection &selection) +{ + QModelIndexList indexes = selection.indexes(); + + if (!indexes.isEmpty()) { + removeAct->setEnabled(true); + editAct->setEnabled(true); + } else { + removeAct->setEnabled(false); + editAct->setEnabled(false); + } +} +//! [4] diff --git a/examples/widgets/itemviews/addressbook/mainwindow.h b/examples/widgets/itemviews/addressbook/mainwindow.h new file mode 100644 index 0000000000..284e492c4a --- /dev/null +++ b/examples/widgets/itemviews/addressbook/mainwindow.h @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include "addresswidget.h" + +//! [0] +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(); + +private slots: + void updateActions(const QItemSelection &selection); + void openFile(); + void saveFile(); + +private: + void createMenus(); + + AddressWidget *addressWidget; + QMenu *fileMenu; + QMenu *toolMenu; + QAction *openAct; + QAction *saveAct; + QAction *exitAct; + QAction *addAct; + QAction *editAct; + QAction *removeAct; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/addressbook/newaddresstab.cpp b/examples/widgets/itemviews/addressbook/newaddresstab.cpp new file mode 100644 index 0000000000..f27789a511 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/newaddresstab.cpp @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "newaddresstab.h" +#include "adddialog.h" + +//! [0] +NewAddressTab::NewAddressTab(QWidget *parent) +{ + Q_UNUSED(parent); + + descriptionLabel = new QLabel(tr("There are currently no contacts in your address book. " + "\nClick Add to add new contacts.")); + + addButton = new QPushButton(tr("Add")); + + connect(addButton, SIGNAL(clicked()), this, SLOT(addEntry())); + + mainLayout = new QVBoxLayout; + mainLayout->addWidget(descriptionLabel); + mainLayout->addWidget(addButton, 0, Qt::AlignCenter); + + setLayout(mainLayout); +} +//! [0] + +//! [1] +void NewAddressTab::addEntry() +{ + AddDialog aDialog; + + if (aDialog.exec()) { + QString name = aDialog.nameText->text(); + QString address = aDialog.addressText->toPlainText(); + + emit sendDetails(name, address); + } +} +//! [1] diff --git a/examples/widgets/itemviews/addressbook/newaddresstab.h b/examples/widgets/itemviews/addressbook/newaddresstab.h new file mode 100644 index 0000000000..4562050f75 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/newaddresstab.h @@ -0,0 +1,74 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef NEWADDRESSTAB_H +#define NEWADDRESSTAB_H + +#include + +QT_BEGIN_NAMESPACE +class QLabel; +class QPushButton; +class QVBoxLayout; +QT_END_NAMESPACE + +//! [0] +class NewAddressTab : public QWidget +{ + Q_OBJECT + +public: + NewAddressTab(QWidget *parent=0); + +public slots: + void addEntry(); + +signals: + void sendDetails(QString name, QString address); + +private: + QLabel *descriptionLabel; + QPushButton *addButton; + QVBoxLayout *mainLayout; + +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/addressbook/tablemodel.cpp b/examples/widgets/itemviews/addressbook/tablemodel.cpp new file mode 100644 index 0000000000..6d99a02b55 --- /dev/null +++ b/examples/widgets/itemviews/addressbook/tablemodel.cpp @@ -0,0 +1,184 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "tablemodel.h" + +//! [0] +TableModel::TableModel(QObject *parent) + : QAbstractTableModel(parent) +{ +} + +TableModel::TableModel(QList< QPair > pairs, QObject *parent) + : QAbstractTableModel(parent) +{ + listOfPairs=pairs; +} +//! [0] + +//! [1] +int TableModel::rowCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return listOfPairs.size(); +} + +int TableModel::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return 2; +} +//! [1] + +//! [2] +QVariant TableModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (index.row() >= listOfPairs.size() || index.row() < 0) + return QVariant(); + + if (role == Qt::DisplayRole) { + QPair pair = listOfPairs.at(index.row()); + + if (index.column() == 0) + return pair.first; + else if (index.column() == 1) + return pair.second; + } + return QVariant(); +} +//! [2] + +//! [3] +QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (role != Qt::DisplayRole) + return QVariant(); + + if (orientation == Qt::Horizontal) { + switch (section) { + case 0: + return tr("Name"); + + case 1: + return tr("Address"); + + default: + return QVariant(); + } + } + return QVariant(); +} +//! [3] + +//! [4] +bool TableModel::insertRows(int position, int rows, const QModelIndex &index) +{ + Q_UNUSED(index); + beginInsertRows(QModelIndex(), position, position+rows-1); + + for (int row=0; row < rows; row++) { + QPair pair(" ", " "); + listOfPairs.insert(position, pair); + } + + endInsertRows(); + return true; +} +//! [4] + +//! [5] +bool TableModel::removeRows(int position, int rows, const QModelIndex &index) +{ + Q_UNUSED(index); + beginRemoveRows(QModelIndex(), position, position+rows-1); + + for (int row=0; row < rows; ++row) { + listOfPairs.removeAt(position); + } + + endRemoveRows(); + return true; +} +//! [5] + +//! [6] +bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role) +{ + if (index.isValid() && role == Qt::EditRole) { + int row = index.row(); + + QPair p = listOfPairs.value(row); + + if (index.column() == 0) + p.first = value.toString(); + else if (index.column() == 1) + p.second = value.toString(); + else + return false; + + listOfPairs.replace(row, p); + emit(dataChanged(index, index)); + + return true; + } + + return false; +} +//! [6] + +//! [7] +Qt::ItemFlags TableModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return Qt::ItemIsEnabled; + + return QAbstractTableModel::flags(index) | Qt::ItemIsEditable; +} +//! [7] + +//! [8] +QList< QPair > TableModel::getList() +{ + return listOfPairs; +} +//! [8] diff --git a/examples/widgets/itemviews/addressbook/tablemodel.h b/examples/widgets/itemviews/addressbook/tablemodel.h new file mode 100644 index 0000000000..bb21af587f --- /dev/null +++ b/examples/widgets/itemviews/addressbook/tablemodel.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TABLEMODEL_H +#define TABLEMODEL_H + +#include +#include +#include + +//! [0] +class TableModel : public QAbstractTableModel +{ + Q_OBJECT + +public: + TableModel(QObject *parent=0); + TableModel(QList< QPair > listofPairs, QObject *parent=0); + + int rowCount(const QModelIndex &parent) const; + int columnCount(const QModelIndex &parent) const; + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role) 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()); + QList< QPair > getList(); + +private: + QList< QPair > listOfPairs; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.desktop b/examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.desktop new file mode 100644 index 0000000000..22621f3ba5 --- /dev/null +++ b/examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Basic Sort Filter Model +Exec=/opt/usr/bin/basicsortfiltermodel +Icon=basicsortfiltermodel +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.pro b/examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.pro new file mode 100644 index 0000000000..75f96e4d48 --- /dev/null +++ b/examples/widgets/itemviews/basicsortfiltermodel/basicsortfiltermodel.pro @@ -0,0 +1,12 @@ +HEADERS = window.h +SOURCES = main.cpp \ + window.cpp +CONFIG += qt + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/basicsortfiltermodel +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/basicsortfiltermodel +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/basicsortfiltermodel/main.cpp b/examples/widgets/itemviews/basicsortfiltermodel/main.cpp new file mode 100644 index 0000000000..00b733090a --- /dev/null +++ b/examples/widgets/itemviews/basicsortfiltermodel/main.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +void addMail(QAbstractItemModel *model, const QString &subject, + const QString &sender, const QDateTime &date) +{ + model->insertRow(0); + model->setData(model->index(0, 0), subject); + model->setData(model->index(0, 1), sender); + model->setData(model->index(0, 2), date); +} + +QAbstractItemModel *createMailModel(QObject *parent) +{ + QStandardItemModel *model = new QStandardItemModel(0, 3, parent); + + model->setHeaderData(0, Qt::Horizontal, QObject::tr("Subject")); + model->setHeaderData(1, Qt::Horizontal, QObject::tr("Sender")); + model->setHeaderData(2, Qt::Horizontal, QObject::tr("Date")); + + addMail(model, "Happy New Year!", "Grace K. ", + QDateTime(QDate(2006, 12, 31), QTime(17, 03))); + addMail(model, "Radically new concept", "Grace K. ", + QDateTime(QDate(2006, 12, 22), QTime(9, 44))); + addMail(model, "Accounts", "pascale@nospam.com", + QDateTime(QDate(2006, 12, 31), QTime(12, 50))); + addMail(model, "Expenses", "Joe Bloggs ", + QDateTime(QDate(2006, 12, 25), QTime(11, 39))); + addMail(model, "Re: Expenses", "Andy ", + QDateTime(QDate(2007, 01, 02), QTime(16, 05))); + addMail(model, "Re: Accounts", "Joe Bloggs ", + QDateTime(QDate(2007, 01, 03), QTime(14, 18))); + addMail(model, "Re: Accounts", "Andy ", + QDateTime(QDate(2007, 01, 03), QTime(14, 26))); + addMail(model, "Sports", "Linda Smith ", + QDateTime(QDate(2007, 01, 05), QTime(11, 33))); + addMail(model, "AW: Sports", "Rolf Newschweinstein ", + QDateTime(QDate(2007, 01, 05), QTime(12, 00))); + addMail(model, "RE: Sports", "Petra Schmidt ", + QDateTime(QDate(2007, 01, 05), QTime(12, 01))); + + return model; +} + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Window window; + window.setSourceModel(createMailModel(&window)); + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/basicsortfiltermodel/window.cpp b/examples/widgets/itemviews/basicsortfiltermodel/window.cpp new file mode 100644 index 0000000000..f7f43c1753 --- /dev/null +++ b/examples/widgets/itemviews/basicsortfiltermodel/window.cpp @@ -0,0 +1,157 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +Window::Window() +{ + proxyModel = new QSortFilterProxyModel; + + sourceView = new QTreeView; + sourceView->setRootIsDecorated(false); + sourceView->setAlternatingRowColors(true); + + proxyView = new QTreeView; + proxyView->setRootIsDecorated(false); + proxyView->setAlternatingRowColors(true); + proxyView->setModel(proxyModel); + proxyView->setSortingEnabled(true); + + sortCaseSensitivityCheckBox = new QCheckBox(tr("Case sensitive sorting")); + filterCaseSensitivityCheckBox = new QCheckBox(tr("Case sensitive filter")); + + filterPatternLineEdit = new QLineEdit; + filterPatternLabel = new QLabel(tr("&Filter pattern:")); + filterPatternLabel->setBuddy(filterPatternLineEdit); + + filterSyntaxComboBox = new QComboBox; + filterSyntaxComboBox->addItem(tr("Regular expression"), QRegExp::RegExp); + filterSyntaxComboBox->addItem(tr("Wildcard"), QRegExp::Wildcard); + filterSyntaxComboBox->addItem(tr("Fixed string"), QRegExp::FixedString); + filterSyntaxLabel = new QLabel(tr("Filter &syntax:")); + filterSyntaxLabel->setBuddy(filterSyntaxComboBox); + + filterColumnComboBox = new QComboBox; + filterColumnComboBox->addItem(tr("Subject")); + filterColumnComboBox->addItem(tr("Sender")); + filterColumnComboBox->addItem(tr("Date")); + filterColumnLabel = new QLabel(tr("Filter &column:")); + filterColumnLabel->setBuddy(filterColumnComboBox); + + connect(filterPatternLineEdit, SIGNAL(textChanged(QString)), + this, SLOT(filterRegExpChanged())); + connect(filterSyntaxComboBox, SIGNAL(currentIndexChanged(int)), + this, SLOT(filterRegExpChanged())); + connect(filterColumnComboBox, SIGNAL(currentIndexChanged(int)), + this, SLOT(filterColumnChanged())); + connect(filterCaseSensitivityCheckBox, SIGNAL(toggled(bool)), + this, SLOT(filterRegExpChanged())); + connect(sortCaseSensitivityCheckBox, SIGNAL(toggled(bool)), + this, SLOT(sortChanged())); + + sourceGroupBox = new QGroupBox(tr("Original Model")); + proxyGroupBox = new QGroupBox(tr("Sorted/Filtered Model")); + + QHBoxLayout *sourceLayout = new QHBoxLayout; + sourceLayout->addWidget(sourceView); + sourceGroupBox->setLayout(sourceLayout); + + QGridLayout *proxyLayout = new QGridLayout; + proxyLayout->addWidget(proxyView, 0, 0, 1, 3); + proxyLayout->addWidget(filterPatternLabel, 1, 0); + proxyLayout->addWidget(filterPatternLineEdit, 1, 1, 1, 2); + proxyLayout->addWidget(filterSyntaxLabel, 2, 0); + proxyLayout->addWidget(filterSyntaxComboBox, 2, 1, 1, 2); + proxyLayout->addWidget(filterColumnLabel, 3, 0); + proxyLayout->addWidget(filterColumnComboBox, 3, 1, 1, 2); + proxyLayout->addWidget(filterCaseSensitivityCheckBox, 4, 0, 1, 2); + proxyLayout->addWidget(sortCaseSensitivityCheckBox, 4, 2); + proxyGroupBox->setLayout(proxyLayout); + + QVBoxLayout *mainLayout = new QVBoxLayout; + + mainLayout->addWidget(sourceGroupBox); + mainLayout->addWidget(proxyGroupBox); + + setLayout(mainLayout); + + setWindowTitle(tr("Basic Sort/Filter Model")); + resize(500, 450); + + proxyView->sortByColumn(1, Qt::AscendingOrder); + filterColumnComboBox->setCurrentIndex(1); + + filterPatternLineEdit->setText("Andy|Grace"); + filterCaseSensitivityCheckBox->setChecked(true); + sortCaseSensitivityCheckBox->setChecked(true); +} + +void Window::setSourceModel(QAbstractItemModel *model) +{ + proxyModel->setSourceModel(model); + sourceView->setModel(model); +} + +void Window::filterRegExpChanged() +{ + QRegExp::PatternSyntax syntax = + QRegExp::PatternSyntax(filterSyntaxComboBox->itemData( + filterSyntaxComboBox->currentIndex()).toInt()); + Qt::CaseSensitivity caseSensitivity = + filterCaseSensitivityCheckBox->isChecked() ? Qt::CaseSensitive + : Qt::CaseInsensitive; + + QRegExp regExp(filterPatternLineEdit->text(), caseSensitivity, syntax); + proxyModel->setFilterRegExp(regExp); +} + +void Window::filterColumnChanged() +{ + proxyModel->setFilterKeyColumn(filterColumnComboBox->currentIndex()); +} + +void Window::sortChanged() +{ + proxyModel->setSortCaseSensitivity( + sortCaseSensitivityCheckBox->isChecked() ? Qt::CaseSensitive + : Qt::CaseInsensitive); +} diff --git a/examples/widgets/itemviews/basicsortfiltermodel/window.h b/examples/widgets/itemviews/basicsortfiltermodel/window.h new file mode 100644 index 0000000000..f672a3eb66 --- /dev/null +++ b/examples/widgets/itemviews/basicsortfiltermodel/window.h @@ -0,0 +1,88 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include + +QT_BEGIN_NAMESPACE +class QAbstractItemModel; +class QCheckBox; +class QComboBox; +class QGroupBox; +class QLabel; +class QLineEdit; +class QSortFilterProxyModel; +class QTreeView; +QT_END_NAMESPACE + +class Window : public QWidget +{ + Q_OBJECT + +public: + Window(); + + void setSourceModel(QAbstractItemModel *model); + +private slots: + void filterRegExpChanged(); + void filterColumnChanged(); + void sortChanged(); + +private: + QSortFilterProxyModel *proxyModel; + + QGroupBox *sourceGroupBox; + QGroupBox *proxyGroupBox; + QTreeView *sourceView; + QTreeView *proxyView; + QCheckBox *filterCaseSensitivityCheckBox; + QCheckBox *sortCaseSensitivityCheckBox; + QLabel *filterPatternLabel; + QLabel *filterSyntaxLabel; + QLabel *filterColumnLabel; + QLineEdit *filterPatternLineEdit; + QComboBox *filterSyntaxComboBox; + QComboBox *filterColumnComboBox; +}; + +#endif diff --git a/examples/widgets/itemviews/chart/chart.desktop b/examples/widgets/itemviews/chart/chart.desktop new file mode 100644 index 0000000000..73e017baeb --- /dev/null +++ b/examples/widgets/itemviews/chart/chart.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Chart +Exec=/opt/usr/bin/chart +Icon=chart +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/chart/chart.pro b/examples/widgets/itemviews/chart/chart.pro new file mode 100644 index 0000000000..310bb85ad7 --- /dev/null +++ b/examples/widgets/itemviews/chart/chart.pro @@ -0,0 +1,18 @@ +HEADERS = mainwindow.h \ + pieview.h +RESOURCES = chart.qrc +SOURCES = main.cpp \ + mainwindow.cpp \ + pieview.cpp +unix:!mac:!vxworks:!integrity:LIBS+= -lm + +TARGET.EPOCHEAPSIZE = 0x200000 0x800000 + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/chart +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.cht +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/chart +INSTALLS += target sources + +QT += widgets + diff --git a/examples/widgets/itemviews/chart/chart.qrc b/examples/widgets/itemviews/chart/chart.qrc new file mode 100644 index 0000000000..7401d4d2f8 --- /dev/null +++ b/examples/widgets/itemviews/chart/chart.qrc @@ -0,0 +1,5 @@ + + + qtdata.cht + + diff --git a/examples/widgets/itemviews/chart/main.cpp b/examples/widgets/itemviews/chart/main.cpp new file mode 100644 index 0000000000..b1c13116c9 --- /dev/null +++ b/examples/widgets/itemviews/chart/main.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(chart); + + QApplication app(argc, argv); + MainWindow window; + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/chart/mainwindow.cpp b/examples/widgets/itemviews/chart/mainwindow.cpp new file mode 100644 index 0000000000..584390252b --- /dev/null +++ b/examples/widgets/itemviews/chart/mainwindow.cpp @@ -0,0 +1,172 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "pieview.h" +#include "mainwindow.h" + +MainWindow::MainWindow() +{ + QMenu *fileMenu = new QMenu(tr("&File"), this); + QAction *openAction = fileMenu->addAction(tr("&Open...")); + openAction->setShortcuts(QKeySequence::Open); + QAction *saveAction = fileMenu->addAction(tr("&Save As...")); + saveAction->setShortcuts(QKeySequence::SaveAs); + QAction *quitAction = fileMenu->addAction(tr("E&xit")); + quitAction->setShortcuts(QKeySequence::Quit); + + setupModel(); + setupViews(); + + connect(openAction, SIGNAL(triggered()), this, SLOT(openFile())); + connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile())); + connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + + menuBar()->addMenu(fileMenu); + statusBar(); + + openFile(":/Charts/qtdata.cht"); + + setWindowTitle(tr("Chart")); + resize(870, 550); +} + +void MainWindow::setupModel() +{ + model = new QStandardItemModel(8, 2, this); + model->setHeaderData(0, Qt::Horizontal, tr("Label")); + model->setHeaderData(1, Qt::Horizontal, tr("Quantity")); +} + +void MainWindow::setupViews() +{ + QSplitter *splitter = new QSplitter; + QTableView *table = new QTableView; + pieChart = new PieView; + splitter->addWidget(table); + splitter->addWidget(pieChart); + splitter->setStretchFactor(0, 0); + splitter->setStretchFactor(1, 1); + + table->setModel(model); + pieChart->setModel(model); + + QItemSelectionModel *selectionModel = new QItemSelectionModel(model); + table->setSelectionModel(selectionModel); + pieChart->setSelectionModel(selectionModel); + + QHeaderView *headerView = table->horizontalHeader(); + headerView->setStretchLastSection(true); + + setCentralWidget(splitter); +} + +void MainWindow::openFile(const QString &path) +{ + QString fileName; + if (path.isNull()) + fileName = QFileDialog::getOpenFileName(this, tr("Choose a data file"), + "", "*.cht"); + else + fileName = path; + + if (!fileName.isEmpty()) { + QFile file(fileName); + + if (file.open(QFile::ReadOnly | QFile::Text)) { + QTextStream stream(&file); + QString line; + + model->removeRows(0, model->rowCount(QModelIndex()), QModelIndex()); + + int row = 0; + do { + line = stream.readLine(); + if (!line.isEmpty()) { + + model->insertRows(row, 1, QModelIndex()); + + QStringList pieces = line.split(",", QString::SkipEmptyParts); + model->setData(model->index(row, 0, QModelIndex()), + pieces.value(0)); + model->setData(model->index(row, 1, QModelIndex()), + pieces.value(1)); + model->setData(model->index(row, 0, QModelIndex()), + QColor(pieces.value(2)), Qt::DecorationRole); + row++; + } + } while (!line.isEmpty()); + + file.close(); + statusBar()->showMessage(tr("Loaded %1").arg(fileName), 2000); + } + } +} + +void MainWindow::saveFile() +{ + QString fileName = QFileDialog::getSaveFileName(this, + tr("Save file as"), "", "*.cht"); + + if (!fileName.isEmpty()) { + QFile file(fileName); + QTextStream stream(&file); + + if (file.open(QFile::WriteOnly | QFile::Text)) { + for (int row = 0; row < model->rowCount(QModelIndex()); ++row) { + + QStringList pieces; + + pieces.append(model->data(model->index(row, 0, QModelIndex()), + Qt::DisplayRole).toString()); + pieces.append(model->data(model->index(row, 1, QModelIndex()), + Qt::DisplayRole).toString()); + pieces.append(model->data(model->index(row, 0, QModelIndex()), + Qt::DecorationRole).toString()); + + stream << pieces.join(",") << "\n"; + } + } + + file.close(); + statusBar()->showMessage(tr("Saved %1").arg(fileName), 2000); + } +} diff --git a/examples/widgets/itemviews/chart/mainwindow.h b/examples/widgets/itemviews/chart/mainwindow.h new file mode 100644 index 0000000000..5ce4f30e32 --- /dev/null +++ b/examples/widgets/itemviews/chart/mainwindow.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +QT_BEGIN_NAMESPACE +class QAbstractItemModel; +class QAbstractItemView; +class QItemSelectionModel; +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(); + +private slots: + void openFile(const QString &path = QString()); + void saveFile(); + +private: + void setupModel(); + void setupViews(); + + QAbstractItemModel *model; + QAbstractItemView *pieChart; + QItemSelectionModel *selectionModel; +}; + +#endif diff --git a/examples/widgets/itemviews/chart/mydata.cht b/examples/widgets/itemviews/chart/mydata.cht new file mode 100644 index 0000000000..029fd81458 --- /dev/null +++ b/examples/widgets/itemviews/chart/mydata.cht @@ -0,0 +1,8 @@ +London,4,red +Stockholm,5,pink +Paris,2,lightgreen +Rome,11,green +Lisbon,9,blue +Madrid,8,lightblue +Berlin,6,magenta +Vienna,7,purple diff --git a/examples/widgets/itemviews/chart/pieview.cpp b/examples/widgets/itemviews/chart/pieview.cpp new file mode 100644 index 0000000000..30f3255689 --- /dev/null +++ b/examples/widgets/itemviews/chart/pieview.cpp @@ -0,0 +1,557 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#ifndef M_PI +#define M_PI 3.1415927 +#endif + +#include "pieview.h" + +PieView::PieView(QWidget *parent) + : QAbstractItemView(parent) +{ + horizontalScrollBar()->setRange(0, 0); + verticalScrollBar()->setRange(0, 0); + + margin = 8; + totalSize = 300; + pieSize = totalSize - 2*margin; + validItems = 0; + totalValue = 0.0; + rubberBand = 0; +} + +void PieView::dataChanged(const QModelIndex &topLeft, + const QModelIndex &bottomRight, + const QVector &) +{ + QAbstractItemView::dataChanged(topLeft, bottomRight); + + validItems = 0; + totalValue = 0.0; + + for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + double value = model()->data(index).toDouble(); + + if (value > 0.0) { + totalValue += value; + validItems++; + } + } + viewport()->update(); +} + +bool PieView::edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) +{ + if (index.column() == 0) + return QAbstractItemView::edit(index, trigger, event); + else + return false; +} + +/* + Returns the item that covers the coordinate given in the view. +*/ + +QModelIndex PieView::indexAt(const QPoint &point) const +{ + if (validItems == 0) + return QModelIndex(); + + // Transform the view coordinates into contents widget coordinates. + int wx = point.x() + horizontalScrollBar()->value(); + int wy = point.y() + verticalScrollBar()->value(); + + if (wx < totalSize) { + double cx = wx - totalSize/2; + double cy = totalSize/2 - wy; // positive cy for items above the center + + // Determine the distance from the center point of the pie chart. + double d = pow(pow(cx, 2) + pow(cy, 2), 0.5); + + if (d == 0 || d > pieSize/2) + return QModelIndex(); + + // Determine the angle of the point. + double angle = (180 / M_PI) * acos(cx/d); + if (cy < 0) + angle = 360 - angle; + + // Find the relevant slice of the pie. + double startAngle = 0.0; + + for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + double value = model()->data(index).toDouble(); + + if (value > 0.0) { + double sliceAngle = 360*value/totalValue; + + if (angle >= startAngle && angle < (startAngle + sliceAngle)) + return model()->index(row, 1, rootIndex()); + + startAngle += sliceAngle; + } + } + } else { + double itemHeight = QFontMetrics(viewOptions().font).height(); + int listItem = int((wy - margin) / itemHeight); + int validRow = 0; + + for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + if (model()->data(index).toDouble() > 0.0) { + + if (listItem == validRow) + return model()->index(row, 0, rootIndex()); + + // Update the list index that corresponds to the next valid row. + validRow++; + } + } + } + + return QModelIndex(); +} + +bool PieView::isIndexHidden(const QModelIndex & /*index*/) const +{ + return false; +} + +/* + Returns the rectangle of the item at position \a index in the + model. The rectangle is in contents coordinates. +*/ + +QRect PieView::itemRect(const QModelIndex &index) const +{ + if (!index.isValid()) + return QRect(); + + // Check whether the index's row is in the list of rows represented + // by slices. + QModelIndex valueIndex; + + if (index.column() != 1) + valueIndex = model()->index(index.row(), 1, rootIndex()); + else + valueIndex = index; + + if (model()->data(valueIndex).toDouble() > 0.0) { + + int listItem = 0; + for (int row = index.row()-1; row >= 0; --row) { + if (model()->data(model()->index(row, 1, rootIndex())).toDouble() > 0.0) + listItem++; + } + + double itemHeight; + + switch (index.column()) { + case 0: + itemHeight = QFontMetrics(viewOptions().font).height(); + + return QRect(totalSize, + int(margin + listItem*itemHeight), + totalSize - margin, int(itemHeight)); + case 1: + return viewport()->rect(); + } + + } + return QRect(); +} + +QRegion PieView::itemRegion(const QModelIndex &index) const +{ + if (!index.isValid()) + return QRegion(); + + if (index.column() != 1) + return itemRect(index); + + if (model()->data(index).toDouble() <= 0.0) + return QRegion(); + + double startAngle = 0.0; + for (int row = 0; row < model()->rowCount(rootIndex()); ++row) { + + QModelIndex sliceIndex = model()->index(row, 1, rootIndex()); + double value = model()->data(sliceIndex).toDouble(); + + if (value > 0.0) { + double angle = 360*value/totalValue; + + if (sliceIndex == index) { + QPainterPath slicePath; + slicePath.moveTo(totalSize/2, totalSize/2); + slicePath.arcTo(margin, margin, margin+pieSize, margin+pieSize, + startAngle, angle); + slicePath.closeSubpath(); + + return QRegion(slicePath.toFillPolygon().toPolygon()); + } + + startAngle += angle; + } + } + + return QRegion(); +} + +int PieView::horizontalOffset() const +{ + return horizontalScrollBar()->value(); +} + +void PieView::mousePressEvent(QMouseEvent *event) +{ + QAbstractItemView::mousePressEvent(event); + origin = event->pos(); + if (!rubberBand) + rubberBand = new QRubberBand(QRubberBand::Rectangle, viewport()); + rubberBand->setGeometry(QRect(origin, QSize())); + rubberBand->show(); +} + +void PieView::mouseMoveEvent(QMouseEvent *event) +{ + if (rubberBand) + rubberBand->setGeometry(QRect(origin, event->pos()).normalized()); + QAbstractItemView::mouseMoveEvent(event); +} + +void PieView::mouseReleaseEvent(QMouseEvent *event) +{ + QAbstractItemView::mouseReleaseEvent(event); + if (rubberBand) + rubberBand->hide(); + viewport()->update(); +} + +QModelIndex PieView::moveCursor(QAbstractItemView::CursorAction cursorAction, + Qt::KeyboardModifiers /*modifiers*/) +{ + QModelIndex current = currentIndex(); + + switch (cursorAction) { + case MoveLeft: + case MoveUp: + if (current.row() > 0) + current = model()->index(current.row() - 1, current.column(), + rootIndex()); + else + current = model()->index(0, current.column(), rootIndex()); + break; + case MoveRight: + case MoveDown: + if (current.row() < rows(current) - 1) + current = model()->index(current.row() + 1, current.column(), + rootIndex()); + else + current = model()->index(rows(current) - 1, current.column(), + rootIndex()); + break; + default: + break; + } + + viewport()->update(); + return current; +} + +void PieView::paintEvent(QPaintEvent *event) +{ + QItemSelectionModel *selections = selectionModel(); + QStyleOptionViewItem option = viewOptions(); + + QBrush background = option.palette.base(); + QPen foreground(option.palette.color(QPalette::WindowText)); + + QPainter painter(viewport()); + painter.setRenderHint(QPainter::Antialiasing); + + painter.fillRect(event->rect(), background); + painter.setPen(foreground); + + // Viewport rectangles + QRect pieRect = QRect(margin, margin, pieSize, pieSize); + + if (validItems > 0) { + + painter.save(); + painter.translate(pieRect.x() - horizontalScrollBar()->value(), + pieRect.y() - verticalScrollBar()->value()); + painter.drawEllipse(0, 0, pieSize, pieSize); + double startAngle = 0.0; + int row; + + for (row = 0; row < model()->rowCount(rootIndex()); ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + double value = model()->data(index).toDouble(); + + if (value > 0.0) { + double angle = 360*value/totalValue; + + QModelIndex colorIndex = model()->index(row, 0, rootIndex()); + QColor color = QColor(model()->data(colorIndex, + Qt::DecorationRole).toString()); + + if (currentIndex() == index) + painter.setBrush(QBrush(color, Qt::Dense4Pattern)); + else if (selections->isSelected(index)) + painter.setBrush(QBrush(color, Qt::Dense3Pattern)); + else + painter.setBrush(QBrush(color)); + + painter.drawPie(0, 0, pieSize, pieSize, int(startAngle*16), + int(angle*16)); + + startAngle += angle; + } + } + painter.restore(); + + int keyNumber = 0; + + for (row = 0; row < model()->rowCount(rootIndex()); ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + double value = model()->data(index).toDouble(); + + if (value > 0.0) { + QModelIndex labelIndex = model()->index(row, 0, rootIndex()); + + QStyleOptionViewItem option = viewOptions(); + option.rect = visualRect(labelIndex); + if (selections->isSelected(labelIndex)) + option.state |= QStyle::State_Selected; + if (currentIndex() == labelIndex) + option.state |= QStyle::State_HasFocus; + itemDelegate()->paint(&painter, option, labelIndex); + + keyNumber++; + } + } + } +} + +void PieView::resizeEvent(QResizeEvent * /* event */) +{ + updateGeometries(); +} + +int PieView::rows(const QModelIndex &index) const +{ + return model()->rowCount(model()->parent(index)); +} + +void PieView::rowsInserted(const QModelIndex &parent, int start, int end) +{ + for (int row = start; row <= end; ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + double value = model()->data(index).toDouble(); + + if (value > 0.0) { + totalValue += value; + validItems++; + } + } + + QAbstractItemView::rowsInserted(parent, start, end); +} + +void PieView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) +{ + for (int row = start; row <= end; ++row) { + + QModelIndex index = model()->index(row, 1, rootIndex()); + double value = model()->data(index).toDouble(); + if (value > 0.0) { + totalValue -= value; + validItems--; + } + } + + QAbstractItemView::rowsAboutToBeRemoved(parent, start, end); +} + +void PieView::scrollContentsBy(int dx, int dy) +{ + viewport()->scroll(dx, dy); +} + +void PieView::scrollTo(const QModelIndex &index, ScrollHint) +{ + QRect area = viewport()->rect(); + QRect rect = visualRect(index); + + if (rect.left() < area.left()) + horizontalScrollBar()->setValue( + horizontalScrollBar()->value() + rect.left() - area.left()); + else if (rect.right() > area.right()) + horizontalScrollBar()->setValue( + horizontalScrollBar()->value() + qMin( + rect.right() - area.right(), rect.left() - area.left())); + + if (rect.top() < area.top()) + verticalScrollBar()->setValue( + verticalScrollBar()->value() + rect.top() - area.top()); + else if (rect.bottom() > area.bottom()) + verticalScrollBar()->setValue( + verticalScrollBar()->value() + qMin( + rect.bottom() - area.bottom(), rect.top() - area.top())); + + update(); +} + +/* + Find the indices corresponding to the extent of the selection. +*/ + +void PieView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) +{ + // Use content widget coordinates because we will use the itemRegion() + // function to check for intersections. + + QRect contentsRect = rect.translated( + horizontalScrollBar()->value(), + verticalScrollBar()->value()).normalized(); + + int rows = model()->rowCount(rootIndex()); + int columns = model()->columnCount(rootIndex()); + QModelIndexList indexes; + + for (int row = 0; row < rows; ++row) { + for (int column = 0; column < columns; ++column) { + QModelIndex index = model()->index(row, column, rootIndex()); + QRegion region = itemRegion(index); + if (region.intersects(contentsRect)) + indexes.append(index); + } + } + + if (indexes.size() > 0) { + int firstRow = indexes[0].row(); + int lastRow = indexes[0].row(); + int firstColumn = indexes[0].column(); + int lastColumn = indexes[0].column(); + + for (int i = 1; i < indexes.size(); ++i) { + firstRow = qMin(firstRow, indexes[i].row()); + lastRow = qMax(lastRow, indexes[i].row()); + firstColumn = qMin(firstColumn, indexes[i].column()); + lastColumn = qMax(lastColumn, indexes[i].column()); + } + + QItemSelection selection( + model()->index(firstRow, firstColumn, rootIndex()), + model()->index(lastRow, lastColumn, rootIndex())); + selectionModel()->select(selection, command); + } else { + QModelIndex noIndex; + QItemSelection selection(noIndex, noIndex); + selectionModel()->select(selection, command); + } + + update(); +} + +void PieView::updateGeometries() +{ + horizontalScrollBar()->setPageStep(viewport()->width()); + horizontalScrollBar()->setRange(0, qMax(0, 2*totalSize - viewport()->width())); + verticalScrollBar()->setPageStep(viewport()->height()); + verticalScrollBar()->setRange(0, qMax(0, totalSize - viewport()->height())); +} + +int PieView::verticalOffset() const +{ + return verticalScrollBar()->value(); +} + +/* + Returns the position of the item in viewport coordinates. +*/ + +QRect PieView::visualRect(const QModelIndex &index) const +{ + QRect rect = itemRect(index); + if (rect.isValid()) + return QRect(rect.left() - horizontalScrollBar()->value(), + rect.top() - verticalScrollBar()->value(), + rect.width(), rect.height()); + else + return rect; +} + +/* + Returns a region corresponding to the selection in viewport coordinates. +*/ + +QRegion PieView::visualRegionForSelection(const QItemSelection &selection) const +{ + int ranges = selection.count(); + + if (ranges == 0) + return QRect(); + + QRegion region; + for (int i = 0; i < ranges; ++i) { + QItemSelectionRange range = selection.at(i); + for (int row = range.top(); row <= range.bottom(); ++row) { + for (int col = range.left(); col <= range.right(); ++col) { + QModelIndex index = model()->index(row, col, rootIndex()); + region += visualRect(index); + } + } + } + return region; +} diff --git a/examples/widgets/itemviews/chart/pieview.h b/examples/widgets/itemviews/chart/pieview.h new file mode 100644 index 0000000000..208159bf73 --- /dev/null +++ b/examples/widgets/itemviews/chart/pieview.h @@ -0,0 +1,114 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PIEVIEW_H +#define PIEVIEW_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE +class QRubberBand; +QT_END_NAMESPACE + +//! [0] +class PieView : public QAbstractItemView +{ + Q_OBJECT + +public: + PieView(QWidget *parent = 0); + + QRect visualRect(const QModelIndex &index) const; + void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible); + QModelIndex indexAt(const QPoint &point) const; + +protected slots: + void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector & = QVector()); + void rowsInserted(const QModelIndex &parent, int start, int end); + void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end); + +protected: + bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event); + QModelIndex moveCursor(QAbstractItemView::CursorAction cursorAction, + Qt::KeyboardModifiers modifiers); + + int horizontalOffset() const; + int verticalOffset() const; + + bool isIndexHidden(const QModelIndex &index) const; + + void setSelection(const QRect&, QItemSelectionModel::SelectionFlags command); + + void mousePressEvent(QMouseEvent *event); + + void mouseMoveEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + + void paintEvent(QPaintEvent *event); + void resizeEvent(QResizeEvent *event); + void scrollContentsBy(int dx, int dy); + + QRegion visualRegionForSelection(const QItemSelection &selection) const; + +private: + QRect itemRect(const QModelIndex &item) const; + QRegion itemRegion(const QModelIndex &index) const; + int rows(const QModelIndex &index = QModelIndex()) const; + void updateGeometries(); + + int margin; + int totalSize; + int pieSize; + int validItems; + double totalValue; + QPoint origin; + QRubberBand *rubberBand; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/chart/qtdata.cht b/examples/widgets/itemviews/chart/qtdata.cht new file mode 100644 index 0000000000..6386246c4b --- /dev/null +++ b/examples/widgets/itemviews/chart/qtdata.cht @@ -0,0 +1,14 @@ +Scientific Research,21,#99e600 +Engineering & Design,18,#99cc00 +Automotive,14,#99b300 +Aerospace,13,#9f991a +Automation & Machine Tools,13,#a48033 +Medical & Bioinformatics,13,#a9664d +Imaging & Special Effects,12,#ae4d66 +Defense,11,#b33380 +Test & Measurement Systems,9,#a64086 +Oil & Gas,9,#994d8d +Entertainment & Broadcasting,7,#8d5a93 +Financial,6,#806699 +Consumer Electronics,4,#8073a6 +Other,38,#8080b3 diff --git a/examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.desktop b/examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.desktop new file mode 100644 index 0000000000..70b966445c --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Color Editor Factory +Exec=/opt/usr/bin/coloreditorfactory +Icon=coloreditorfactory +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.pro b/examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.pro new file mode 100644 index 0000000000..07e1296e06 --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/coloreditorfactory.pro @@ -0,0 +1,14 @@ +HEADERS = colorlisteditor.h \ + window.h +SOURCES = colorlisteditor.cpp \ + window.cpp \ + main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/coloreditorfactory +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/coloreditorfactory +INSTALLS += target sources + +QT += widgets + diff --git a/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp new file mode 100644 index 0000000000..e8f1f2d719 --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.cpp @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "colorlisteditor.h" + +ColorListEditor::ColorListEditor(QWidget *widget) : QComboBox(widget) +{ + populateList(); +} + +//! [0] +QColor ColorListEditor::color() const +{ + return qvariant_cast(itemData(currentIndex(), Qt::DecorationRole)); +} +//! [0] + +//! [1] +void ColorListEditor::setColor(QColor color) +{ + setCurrentIndex(findData(color, int(Qt::DecorationRole))); +} +//! [1] + +//! [2] +void ColorListEditor::populateList() +{ + QStringList colorNames = QColor::colorNames(); + + for (int i = 0; i < colorNames.size(); ++i) { + QColor color(colorNames[i]); + + insertItem(i, colorNames[i]); + setItemData(i, color, Qt::DecorationRole); + } +} +//! [2] diff --git a/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h new file mode 100644 index 0000000000..13ece8ef6d --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/colorlisteditor.h @@ -0,0 +1,69 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef COLORLISTEDITOR_H +#define COLORLISTEDITOR_H + +#include + +QT_BEGIN_NAMESPACE +class QColor; +class QWidget; +QT_END_NAMESPACE + +//! [0] +class ColorListEditor : public QComboBox +{ + Q_OBJECT + Q_PROPERTY(QColor color READ color WRITE setColor USER true) + +public: + ColorListEditor(QWidget *widget = 0); + +public: + QColor color() const; + void setColor(QColor c); + +private: + void populateList(); +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/coloreditorfactory/main.cpp b/examples/widgets/itemviews/coloreditorfactory/main.cpp new file mode 100644 index 0000000000..5bbe817214 --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/main.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +int main(int argv, char **args) +{ + QApplication app(argv, args); + + Window window; + window.show(); + + return app.exec(); +} diff --git a/examples/widgets/itemviews/coloreditorfactory/window.cpp b/examples/widgets/itemviews/coloreditorfactory/window.cpp new file mode 100644 index 0000000000..5c1b03ebbe --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/window.cpp @@ -0,0 +1,94 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" +#include "colorlisteditor.h" + +//! [0] +Window::Window() +{ + QItemEditorFactory *factory = new QItemEditorFactory; + + QItemEditorCreatorBase *colorListCreator = + new QStandardItemEditorCreator(); + + factory->registerEditor(QVariant::Color, colorListCreator); + + QItemEditorFactory::setDefaultFactory(factory); + + createGUI(); +} +//! [0] + +void Window::createGUI() +{ + QList > list; + list << QPair(tr("Alice"), QColor("aliceblue")) << + QPair(tr("Neptun"), QColor("aquamarine")) << + QPair(tr("Ferdinand"), QColor("springgreen")); + + QTableWidget *table = new QTableWidget(3, 2); + table->setHorizontalHeaderLabels(QStringList() << tr("Name") + << tr("Hair Color")); + table->verticalHeader()->setVisible(false); + table->resize(150, 50); + + for (int i = 0; i < 3; ++i) { + QPair pair = list.at(i); + + QTableWidgetItem *nameItem = new QTableWidgetItem(pair.first); + QTableWidgetItem *colorItem = new QTableWidgetItem; + colorItem->setData(Qt::DisplayRole, pair.second); + + table->setItem(i, 0, nameItem); + table->setItem(i, 1, colorItem); + } + table->resizeColumnToContents(0); + table->horizontalHeader()->setStretchLastSection(true); + + QGridLayout *layout = new QGridLayout; + layout->addWidget(table, 0, 0); + + setLayout(layout); + + setWindowTitle(tr("Color Editor Factory")); +} diff --git a/examples/widgets/itemviews/coloreditorfactory/window.h b/examples/widgets/itemviews/coloreditorfactory/window.h new file mode 100644 index 0000000000..65a9c8e854 --- /dev/null +++ b/examples/widgets/itemviews/coloreditorfactory/window.h @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include + +class Window : public QWidget +{ + Q_OBJECT + +public: + Window(); + +private: + void createGUI(); +}; + +#endif diff --git a/examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.desktop b/examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.desktop new file mode 100644 index 0000000000..3bbf6ad5f3 --- /dev/null +++ b/examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Combo Widget Mapper +Exec=/opt/usr/bin/combowidgetmapper +Icon=combowidgetmapper +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.pro b/examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.pro new file mode 100644 index 0000000000..9ea1fa0e25 --- /dev/null +++ b/examples/widgets/itemviews/combowidgetmapper/combowidgetmapper.pro @@ -0,0 +1,11 @@ +HEADERS = window.h +SOURCES = main.cpp \ + window.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/combowidgetmapper +sources.files = $$SOURCES $$HEADERS *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/combowidgetmapper +INSTALLS += target sources +QT += widgets + diff --git a/examples/widgets/itemviews/combowidgetmapper/main.cpp b/examples/widgets/itemviews/combowidgetmapper/main.cpp new file mode 100644 index 0000000000..0fc4966ccf --- /dev/null +++ b/examples/widgets/itemviews/combowidgetmapper/main.cpp @@ -0,0 +1,51 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + Window window; + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/combowidgetmapper/window.cpp b/examples/widgets/itemviews/combowidgetmapper/window.cpp new file mode 100644 index 0000000000..8c735c04c5 --- /dev/null +++ b/examples/widgets/itemviews/combowidgetmapper/window.cpp @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "window.h" + +//! [Set up widgets] +Window::Window(QWidget *parent) + : QWidget(parent) +{ + setupModel(); + + nameLabel = new QLabel(tr("Na&me:")); + nameEdit = new QLineEdit(); + addressLabel = new QLabel(tr("&Address:")); + addressEdit = new QTextEdit(); + typeLabel = new QLabel(tr("&Type:")); + typeComboBox = new QComboBox(); + nextButton = new QPushButton(tr("&Next")); + previousButton = new QPushButton(tr("&Previous")); + + nameLabel->setBuddy(nameEdit); + addressLabel->setBuddy(addressEdit); + typeLabel->setBuddy(typeComboBox); + + typeComboBox->setModel(typeModel); +//! [Set up widgets] + +//! [Set up the mapper] + mapper = new QDataWidgetMapper(this); + mapper->setModel(model); + mapper->addMapping(nameEdit, 0); + mapper->addMapping(addressEdit, 1); + mapper->addMapping(typeComboBox, 2, "currentIndex"); +//! [Set up the mapper] + +//! [Set up connections and layouts] + connect(previousButton, SIGNAL(clicked()), + mapper, SLOT(toPrevious())); + connect(nextButton, SIGNAL(clicked()), + mapper, SLOT(toNext())); + connect(mapper, SIGNAL(currentIndexChanged(int)), + this, SLOT(updateButtons(int))); + + QGridLayout *layout = new QGridLayout(); + layout->addWidget(nameLabel, 0, 0, 1, 1); + layout->addWidget(nameEdit, 0, 1, 1, 1); + layout->addWidget(previousButton, 0, 2, 1, 1); + layout->addWidget(addressLabel, 1, 0, 1, 1); + layout->addWidget(addressEdit, 1, 1, 2, 1); + layout->addWidget(nextButton, 1, 2, 1, 1); + layout->addWidget(typeLabel, 3, 0, 1, 1); + layout->addWidget(typeComboBox, 3, 1, 1, 1); + setLayout(layout); + + setWindowTitle(tr("Delegate Widget Mapper")); + mapper->toFirst(); +} +//! [Set up connections and layouts] + +//! [Set up the model] +void Window::setupModel() +{ + QStringList items; + items << tr("Home") << tr("Work") << tr("Other"); + typeModel = new QStringListModel(items, this); + + model = new QStandardItemModel(5, 3, this); + QStringList names; + names << "Alice" << "Bob" << "Carol" << "Donald" << "Emma"; + QStringList addresses; + addresses << "123 Main Street
Market Town
" + << "PO Box 32
Mail Handling Service" + "
Service City
" + << "The Lighthouse
Remote Island
" + << "47338 Park Avenue
Big City
" + << "Research Station
Base Camp
Big Mountain
"; + + QStringList types; + types << "0" << "1" << "2" << "0" << "2"; + + for (int row = 0; row < 5; ++row) { + QStandardItem *item = new QStandardItem(names[row]); + model->setItem(row, 0, item); + item = new QStandardItem(addresses[row]); + model->setItem(row, 1, item); + item = new QStandardItem(types[row]); + model->setItem(row, 2, item); + } +} +//! [Set up the model] + +//! [Slot for updating the buttons] +void Window::updateButtons(int row) +{ + previousButton->setEnabled(row > 0); + nextButton->setEnabled(row < model->rowCount() - 1); +} +//! [Slot for updating the buttons] diff --git a/examples/widgets/itemviews/combowidgetmapper/window.h b/examples/widgets/itemviews/combowidgetmapper/window.h new file mode 100644 index 0000000000..8ec5523cf1 --- /dev/null +++ b/examples/widgets/itemviews/combowidgetmapper/window.h @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include + +QT_BEGIN_NAMESPACE +class QComboBox; +class QDataWidgetMapper; +class QLabel; +class QLineEdit; +class QPushButton; +class QStandardItemModel; +class QStringListModel; +class QTextEdit; +QT_END_NAMESPACE + +//! [Window definition] +class Window : public QWidget +{ + Q_OBJECT + +public: + Window(QWidget *parent = 0); + +private slots: + void updateButtons(int row); + +private: + void setupModel(); + + QLabel *nameLabel; + QLabel *addressLabel; + QLabel *typeLabel; + QLineEdit *nameEdit; + QTextEdit *addressEdit; + QComboBox *typeComboBox; + QPushButton *nextButton; + QPushButton *previousButton; + + QStandardItemModel *model; + QStringListModel *typeModel; + QDataWidgetMapper *mapper; +}; +//! [Window definition] + +#endif diff --git a/examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.desktop b/examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.desktop new file mode 100644 index 0000000000..3c961f7e65 --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Custom Sort Filter Model +Exec=/opt/usr/bin/customsortfiltermodel +Icon=customsortfiltermodel +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.pro b/examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.pro new file mode 100644 index 0000000000..a2288b953c --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/customsortfiltermodel.pro @@ -0,0 +1,14 @@ +HEADERS = mysortfilterproxymodel.h \ + window.h +SOURCES = main.cpp \ + mysortfilterproxymodel.cpp \ + window.cpp +CONFIG += qt + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/customsortfiltermodel +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/customsortfiltermodel +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/customsortfiltermodel/main.cpp b/examples/widgets/itemviews/customsortfiltermodel/main.cpp new file mode 100644 index 0000000000..6df986324e --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/main.cpp @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +void addMail(QAbstractItemModel *model, const QString &subject, + const QString &sender, const QDateTime &date) +{ + model->insertRow(0); + model->setData(model->index(0, 0), subject); + model->setData(model->index(0, 1), sender); + model->setData(model->index(0, 2), date); +} + +QAbstractItemModel *createMailModel(QObject *parent) +{ + QStandardItemModel *model = new QStandardItemModel(0, 3, parent); + + model->setHeaderData(0, Qt::Horizontal, QObject::tr("Subject")); + model->setHeaderData(1, Qt::Horizontal, QObject::tr("Sender")); + model->setHeaderData(2, Qt::Horizontal, QObject::tr("Date")); + + addMail(model, "Happy New Year!", "Grace K. ", + QDateTime(QDate(2006, 12, 31), QTime(17, 03))); + addMail(model, "Radically new concept", "Grace K. ", + QDateTime(QDate(2006, 12, 22), QTime(9, 44))); + addMail(model, "Accounts", "pascale@nospam.com", + QDateTime(QDate(2006, 12, 31), QTime(12, 50))); + addMail(model, "Expenses", "Joe Bloggs ", + QDateTime(QDate(2006, 12, 25), QTime(11, 39))); + addMail(model, "Re: Expenses", "Andy ", + QDateTime(QDate(2007, 01, 02), QTime(16, 05))); + addMail(model, "Re: Accounts", "Joe Bloggs ", + QDateTime(QDate(2007, 01, 03), QTime(14, 18))); + addMail(model, "Re: Accounts", "Andy ", + QDateTime(QDate(2007, 01, 03), QTime(14, 26))); + addMail(model, "Sports", "Linda Smith ", + QDateTime(QDate(2007, 01, 05), QTime(11, 33))); + addMail(model, "AW: Sports", "Rolf Newschweinstein ", + QDateTime(QDate(2007, 01, 05), QTime(12, 00))); + addMail(model, "RE: Sports", "Petra Schmidt ", + QDateTime(QDate(2007, 01, 05), QTime(12, 01))); + + return model; +} + +//! [0] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Window window; + window.setSourceModel(createMailModel(&window)); + window.show(); + return app.exec(); +} +//! [0] diff --git a/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp b/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp new file mode 100644 index 0000000000..3100efa4ac --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mysortfilterproxymodel.h" + +//! [0] +MySortFilterProxyModel::MySortFilterProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) +{ +} +//! [0] + +//! [1] +void MySortFilterProxyModel::setFilterMinimumDate(const QDate &date) +{ + minDate = date; + invalidateFilter(); +} +//! [1] + +//! [2] +void MySortFilterProxyModel::setFilterMaximumDate(const QDate &date) +{ + maxDate = date; + invalidateFilter(); +} +//! [2] + +//! [3] +bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow, + const QModelIndex &sourceParent) const +{ + QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); + QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent); + QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent); + + return (sourceModel()->data(index0).toString().contains(filterRegExp()) + || sourceModel()->data(index1).toString().contains(filterRegExp())) + && dateInRange(sourceModel()->data(index2).toDate()); +} +//! [3] + +//! [4] //! [5] +bool MySortFilterProxyModel::lessThan(const QModelIndex &left, + const QModelIndex &right) const +{ + QVariant leftData = sourceModel()->data(left); + QVariant rightData = sourceModel()->data(right); +//! [4] + +//! [6] + if (leftData.type() == QVariant::DateTime) { + return leftData.toDateTime() < rightData.toDateTime(); + } else { + QRegExp *emailPattern = new QRegExp("([\\w\\.]*@[\\w\\.]*)"); + + QString leftString = leftData.toString(); + if(left.column() == 1 && emailPattern->indexIn(leftString) != -1) + leftString = emailPattern->cap(1); + + QString rightString = rightData.toString(); + if(right.column() == 1 && emailPattern->indexIn(rightString) != -1) + rightString = emailPattern->cap(1); + + return QString::localeAwareCompare(leftString, rightString) < 0; + } +} +//! [5] //! [6] + +//! [7] +bool MySortFilterProxyModel::dateInRange(const QDate &date) const +{ + return (!minDate.isValid() || date > minDate) + && (!maxDate.isValid() || date < maxDate); +} +//! [7] diff --git a/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.h b/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.h new file mode 100644 index 0000000000..8ca3e10fd5 --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/mysortfilterproxymodel.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MYSORTFILTERPROXYMODEL_H +#define MYSORTFILTERPROXYMODEL_H + +#include +#include + +//! [0] +class MySortFilterProxyModel : public QSortFilterProxyModel +{ + Q_OBJECT + +public: + MySortFilterProxyModel(QObject *parent = 0); + + QDate filterMinimumDate() const { return minDate; } + void setFilterMinimumDate(const QDate &date); + + QDate filterMaximumDate() const { return maxDate; } + void setFilterMaximumDate(const QDate &date); + +protected: + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; + bool lessThan(const QModelIndex &left, const QModelIndex &right) const; + +private: + bool dateInRange(const QDate &date) const; + + QDate minDate; + QDate maxDate; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/customsortfiltermodel/window.cpp b/examples/widgets/itemviews/customsortfiltermodel/window.cpp new file mode 100644 index 0000000000..0a8799dccb --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/window.cpp @@ -0,0 +1,166 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mysortfilterproxymodel.h" +#include "window.h" + +//! [0] +Window::Window() +{ + proxyModel = new MySortFilterProxyModel(this); + //! [0] + + //! [1] + sourceView = new QTreeView; + sourceView->setRootIsDecorated(false); + sourceView->setAlternatingRowColors(true); + //! [1] + + QHBoxLayout *sourceLayout = new QHBoxLayout; + //! [2] + sourceLayout->addWidget(sourceView); + sourceGroupBox = new QGroupBox(tr("Original Model")); + sourceGroupBox->setLayout(sourceLayout); + //! [2] + + //! [3] + filterCaseSensitivityCheckBox = new QCheckBox(tr("Case sensitive filter")); + filterCaseSensitivityCheckBox->setChecked(true); + + filterPatternLineEdit = new QLineEdit; + filterPatternLineEdit->setText("Grace|Sports"); + + filterPatternLabel = new QLabel(tr("&Filter pattern:")); + filterPatternLabel->setBuddy(filterPatternLineEdit); + + filterSyntaxComboBox = new QComboBox; + filterSyntaxComboBox->addItem(tr("Regular expression"), QRegExp::RegExp); + filterSyntaxComboBox->addItem(tr("Wildcard"), QRegExp::Wildcard); + filterSyntaxComboBox->addItem(tr("Fixed string"), QRegExp::FixedString); + + fromDateEdit = new QDateEdit; + fromDateEdit->setDate(QDate(1970, 01, 01)); + fromLabel = new QLabel(tr("F&rom:")); + fromLabel->setBuddy(fromDateEdit); + + toDateEdit = new QDateEdit; + toDateEdit->setDate(QDate(2099, 12, 31)); + toLabel = new QLabel(tr("&To:")); + toLabel->setBuddy(toDateEdit); + + connect(filterPatternLineEdit, SIGNAL(textChanged(QString)), + this, SLOT(textFilterChanged())); + connect(filterSyntaxComboBox, SIGNAL(currentIndexChanged(int)), + this, SLOT(textFilterChanged())); + connect(filterCaseSensitivityCheckBox, SIGNAL(toggled(bool)), + this, SLOT(textFilterChanged())); + connect(fromDateEdit, SIGNAL(dateChanged(QDate)), + this, SLOT(dateFilterChanged())); + connect(toDateEdit, SIGNAL(dateChanged(QDate)), + //! [3] //! [4] + this, SLOT(dateFilterChanged())); + //! [4] + + //! [5] + proxyView = new QTreeView; + proxyView->setRootIsDecorated(false); + proxyView->setAlternatingRowColors(true); + proxyView->setModel(proxyModel); + proxyView->setSortingEnabled(true); + proxyView->sortByColumn(1, Qt::AscendingOrder); + + QGridLayout *proxyLayout = new QGridLayout; + proxyLayout->addWidget(proxyView, 0, 0, 1, 3); + proxyLayout->addWidget(filterPatternLabel, 1, 0); + proxyLayout->addWidget(filterPatternLineEdit, 1, 1); + proxyLayout->addWidget(filterSyntaxComboBox, 1, 2); + proxyLayout->addWidget(filterCaseSensitivityCheckBox, 2, 0, 1, 3); + proxyLayout->addWidget(fromLabel, 3, 0); + proxyLayout->addWidget(fromDateEdit, 3, 1, 1, 2); + proxyLayout->addWidget(toLabel, 4, 0); + proxyLayout->addWidget(toDateEdit, 4, 1, 1, 2); + + proxyGroupBox = new QGroupBox(tr("Sorted/Filtered Model")); + proxyGroupBox->setLayout(proxyLayout); + //! [5] + + //! [6] + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(sourceGroupBox); + mainLayout->addWidget(proxyGroupBox); + setLayout(mainLayout); + + setWindowTitle(tr("Custom Sort/Filter Model")); + resize(500, 450); +} +//! [6] + +//! [7] +void Window::setSourceModel(QAbstractItemModel *model) +{ + proxyModel->setSourceModel(model); + sourceView->setModel(model); +} +//! [7] + +//! [8] +void Window::textFilterChanged() +{ + QRegExp::PatternSyntax syntax = + QRegExp::PatternSyntax(filterSyntaxComboBox->itemData( + filterSyntaxComboBox->currentIndex()).toInt()); + Qt::CaseSensitivity caseSensitivity = + filterCaseSensitivityCheckBox->isChecked() ? Qt::CaseSensitive + : Qt::CaseInsensitive; + + QRegExp regExp(filterPatternLineEdit->text(), caseSensitivity, syntax); + proxyModel->setFilterRegExp(regExp); +} +//! [8] + +//! [9] +void Window::dateFilterChanged() +{ + proxyModel->setFilterMinimumDate(fromDateEdit->date()); + proxyModel->setFilterMaximumDate(toDateEdit->date()); +} +//! [9] diff --git a/examples/widgets/itemviews/customsortfiltermodel/window.h b/examples/widgets/itemviews/customsortfiltermodel/window.h new file mode 100644 index 0000000000..36650aedad --- /dev/null +++ b/examples/widgets/itemviews/customsortfiltermodel/window.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include + +QT_BEGIN_NAMESPACE +class QAbstractItemModel; +class QCheckBox; +class QComboBox; +class QDateEdit; +class QGroupBox; +class QLabel; +class QLineEdit; +class QTreeView; +QT_END_NAMESPACE +class MySortFilterProxyModel; + +//! [0] +class Window : public QWidget +{ + Q_OBJECT + +public: + Window(); + + void setSourceModel(QAbstractItemModel *model); + +private slots: + void textFilterChanged(); + void dateFilterChanged(); + +private: + MySortFilterProxyModel *proxyModel; + + QGroupBox *sourceGroupBox; + QGroupBox *proxyGroupBox; + QTreeView *sourceView; + QTreeView *proxyView; + QCheckBox *filterCaseSensitivityCheckBox; + QLabel *filterPatternLabel; + QLabel *fromLabel; + QLabel *toLabel; + QLineEdit *filterPatternLineEdit; + QComboBox *filterSyntaxComboBox; + QDateEdit *fromDateEdit; + QDateEdit *toDateEdit; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/dirview/dirview.desktop b/examples/widgets/itemviews/dirview/dirview.desktop new file mode 100644 index 0000000000..51ec4df26c --- /dev/null +++ b/examples/widgets/itemviews/dirview/dirview.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Dir View +Exec=/opt/usr/bin/dirview +Icon=dirview +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/dirview/dirview.pro b/examples/widgets/itemviews/dirview/dirview.pro new file mode 100644 index 0000000000..825f20c630 --- /dev/null +++ b/examples/widgets/itemviews/dirview/dirview.pro @@ -0,0 +1,9 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/dirview +sources.files = $$SOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/dirview +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/dirview/main.cpp b/examples/widgets/itemviews/dirview/main.cpp new file mode 100644 index 0000000000..55083afa8f --- /dev/null +++ b/examples/widgets/itemviews/dirview/main.cpp @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QFileSystemModel model; + model.setRootPath(""); + QTreeView tree; + tree.setModel(&model); + + // Demonstrating look and feel features + tree.setAnimated(false); + tree.setIndentation(20); + tree.setSortingEnabled(true); + + tree.setWindowTitle(QObject::tr("Dir View")); + tree.resize(640, 480); + tree.show(); + + return app.exec(); +} diff --git a/examples/widgets/itemviews/editabletreemodel/default.txt b/examples/widgets/itemviews/editabletreemodel/default.txt new file mode 100644 index 0000000000..2b2fb579ae --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/default.txt @@ -0,0 +1,40 @@ +Getting Started How to familiarize yourself with Qt Designer + Launching Designer Running the Qt Designer application + The User Interface How to interact with Qt Designer + +Designing a Component Creating a GUI for your application + Creating a Dialog How to create a dialog + Composing the Dialog Putting widgets into the dialog example + Creating a Layout Arranging widgets on a form + Signal and Slot Connections Making widget communicate with each other + +Using a Component in Your Application Generating code from forms + The Direct Approach Using a form without any adjustments + The Single Inheritance Approach Subclassing a form's base class + The Multiple Inheritance Approach Subclassing the form itself + Automatic Connections Connecting widgets using a naming scheme + A Dialog Without Auto-Connect How to connect widgets without a naming scheme + A Dialog With Auto-Connect Using automatic connections + +Form Editing Mode How to edit a form in Qt Designer + Managing Forms Loading and saving forms + Editing a Form Basic editing techniques + The Property Editor Changing widget properties + The Object Inspector Examining the hierarchy of objects on a form + Layouts Objects that arrange widgets on a form + Applying and Breaking Layouts Managing widgets in layouts + Horizontal and Vertical Layouts Standard row and column layouts + The Grid Layout Arranging widgets in a matrix + Previewing Forms Checking that the design works + +Using Containers How to group widgets together + General Features Common container features + Frames QFrame + Group Boxes QGroupBox + Stacked Widgets QStackedWidget + Tab Widgets QTabWidget + Toolbox Widgets QToolBox + +Connection Editing Mode Connecting widgets together with signals and slots + Connecting Objects Making connections in Qt Designer + Editing Connections Changing existing connections diff --git a/examples/widgets/itemviews/editabletreemodel/editabletreemodel.desktop b/examples/widgets/itemviews/editabletreemodel/editabletreemodel.desktop new file mode 100644 index 0000000000..17d17330df --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/editabletreemodel.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Editable Tree Model +Exec=/opt/usr/bin/editabletreemodel +Icon=editabletreemodel +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/editabletreemodel/editabletreemodel.pro b/examples/widgets/itemviews/editabletreemodel/editabletreemodel.pro new file mode 100644 index 0000000000..f86298542d --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/editabletreemodel.pro @@ -0,0 +1,18 @@ +FORMS = mainwindow.ui +HEADERS = mainwindow.h \ + treeitem.h \ + treemodel.h +RESOURCES = editabletreemodel.qrc +SOURCES = mainwindow.cpp \ + treeitem.cpp \ + treemodel.cpp \ + main.cpp +CONFIG += qt + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/editabletreemodel +sources.files = $$FORMS $$HEADERS $$RESOURCES $$SOURCES *.pro *.txt +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/editabletreemodel +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/editabletreemodel/editabletreemodel.qrc b/examples/widgets/itemviews/editabletreemodel/editabletreemodel.qrc new file mode 100644 index 0000000000..2fb48f2e62 --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/editabletreemodel.qrc @@ -0,0 +1,5 @@ + + + default.txt + + diff --git a/examples/widgets/itemviews/editabletreemodel/main.cpp b/examples/widgets/itemviews/editabletreemodel/main.cpp new file mode 100644 index 0000000000..516adf1543 --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/main.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(editabletreemodel); + + QApplication app(argc, argv); + MainWindow window; + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp b/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp new file mode 100644 index 0000000000..115b02e28e --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.cpp @@ -0,0 +1,181 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" +#include "treemodel.h" + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ + setupUi(this); + + + QStringList headers; + headers << tr("Title") << tr("Description"); + + QFile file(":/default.txt"); + file.open(QIODevice::ReadOnly); + TreeModel *model = new TreeModel(headers, file.readAll()); + file.close(); + + view->setModel(model); + for (int column = 0; column < model->columnCount(); ++column) + view->resizeColumnToContents(column); + + connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + + connect(view->selectionModel(), + SIGNAL(selectionChanged(const QItemSelection &, + const QItemSelection &)), + this, SLOT(updateActions())); + + connect(actionsMenu, SIGNAL(aboutToShow()), this, SLOT(updateActions())); + connect(insertRowAction, SIGNAL(triggered()), this, SLOT(insertRow())); + connect(insertColumnAction, SIGNAL(triggered()), this, SLOT(insertColumn())); + connect(removeRowAction, SIGNAL(triggered()), this, SLOT(removeRow())); + connect(removeColumnAction, SIGNAL(triggered()), this, SLOT(removeColumn())); + connect(insertChildAction, SIGNAL(triggered()), this, SLOT(insertChild())); + + updateActions(); +} + +void MainWindow::insertChild() +{ + QModelIndex index = view->selectionModel()->currentIndex(); + QAbstractItemModel *model = view->model(); + + if (model->columnCount(index) == 0) { + if (!model->insertColumn(0, index)) + return; + } + + if (!model->insertRow(0, index)) + return; + + for (int column = 0; column < model->columnCount(index); ++column) { + QModelIndex child = model->index(0, column, index); + model->setData(child, QVariant("[No data]"), Qt::EditRole); + if (!model->headerData(column, Qt::Horizontal).isValid()) + model->setHeaderData(column, Qt::Horizontal, QVariant("[No header]"), + Qt::EditRole); + } + + view->selectionModel()->setCurrentIndex(model->index(0, 0, index), + QItemSelectionModel::ClearAndSelect); + updateActions(); +} + +bool MainWindow::insertColumn(const QModelIndex &parent) +{ + QAbstractItemModel *model = view->model(); + int column = view->selectionModel()->currentIndex().column(); + + // Insert a column in the parent item. + bool changed = model->insertColumn(column + 1, parent); + if (changed) + model->setHeaderData(column + 1, Qt::Horizontal, QVariant("[No header]"), + Qt::EditRole); + + updateActions(); + + return changed; +} + +void MainWindow::insertRow() +{ + QModelIndex index = view->selectionModel()->currentIndex(); + QAbstractItemModel *model = view->model(); + + if (!model->insertRow(index.row()+1, index.parent())) + return; + + updateActions(); + + for (int column = 0; column < model->columnCount(index.parent()); ++column) { + QModelIndex child = model->index(index.row()+1, column, index.parent()); + model->setData(child, QVariant("[No data]"), Qt::EditRole); + } +} + +bool MainWindow::removeColumn(const QModelIndex &parent) +{ + QAbstractItemModel *model = view->model(); + int column = view->selectionModel()->currentIndex().column(); + + // Insert columns in each child of the parent item. + bool changed = model->removeColumn(column, parent); + + if (!parent.isValid() && changed) + updateActions(); + + return changed; +} + +void MainWindow::removeRow() +{ + QModelIndex index = view->selectionModel()->currentIndex(); + QAbstractItemModel *model = view->model(); + if (model->removeRow(index.row(), index.parent())) + updateActions(); +} + +void MainWindow::updateActions() +{ + bool hasSelection = !view->selectionModel()->selection().isEmpty(); + removeRowAction->setEnabled(hasSelection); + removeColumnAction->setEnabled(hasSelection); + + bool hasCurrent = view->selectionModel()->currentIndex().isValid(); + insertRowAction->setEnabled(hasCurrent); + insertColumnAction->setEnabled(hasCurrent); + + if (hasCurrent) { + view->closePersistentEditor(view->selectionModel()->currentIndex()); + + int row = view->selectionModel()->currentIndex().row(); + int column = view->selectionModel()->currentIndex().column(); + if (view->selectionModel()->currentIndex().parent().isValid()) + statusBar()->showMessage(tr("Position: (%1,%2)").arg(row).arg(column)); + else + statusBar()->showMessage(tr("Position: (%1,%2) in top level").arg(row).arg(column)); + } +} diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.h b/examples/widgets/itemviews/editabletreemodel/mainwindow.h new file mode 100644 index 0000000000..e45037c2e0 --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.h @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include + +#include "ui_mainwindow.h" + +class QAction; +class QTreeView; +class QWidget; + +class MainWindow : public QMainWindow, private Ui::MainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = 0); + +public slots: + void updateActions(); + +private slots: + void insertChild(); + bool insertColumn(const QModelIndex &parent = QModelIndex()); + void insertRow(); + bool removeColumn(const QModelIndex &parent = QModelIndex()); + void removeRow(); +}; + +#endif diff --git a/examples/widgets/itemviews/editabletreemodel/mainwindow.ui b/examples/widgets/itemviews/editabletreemodel/mainwindow.ui new file mode 100644 index 0000000000..2ad084ae24 --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/mainwindow.ui @@ -0,0 +1,128 @@ + + MainWindow + + + + 0 + 0 + 573 + 468 + + + + Editable Tree Model + + + + + 0 + + + 0 + + + + + true + + + QAbstractItemView::SelectItems + + + QAbstractItemView::ScrollPerPixel + + + false + + + true + + + + + + + + + 0 + 0 + 573 + 31 + + + + + &File + + + + + + &Actions + + + + + + + + + + + + + + + + E&xit + + + Ctrl+Q + + + + + Insert Row + + + Ctrl+I, R + + + + + Remove Row + + + Ctrl+R, R + + + + + Insert Column + + + Ctrl+I, C + + + + + Remove Column + + + Ctrl+R, C + + + + + Insert Child + + + Ctrl+N + + + + + + + + diff --git a/examples/widgets/itemviews/editabletreemodel/treeitem.cpp b/examples/widgets/itemviews/editabletreemodel/treeitem.cpp new file mode 100644 index 0000000000..c728f21a92 --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/treeitem.cpp @@ -0,0 +1,179 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + treeitem.cpp + + A container for items of data supplied by the simple tree model. +*/ + +#include + +#include "treeitem.h" + +//! [0] +TreeItem::TreeItem(const QVector &data, TreeItem *parent) +{ + parentItem = parent; + itemData = data; +} +//! [0] + +//! [1] +TreeItem::~TreeItem() +{ + qDeleteAll(childItems); +} +//! [1] + +//! [2] +TreeItem *TreeItem::child(int number) +{ + return childItems.value(number); +} +//! [2] + +//! [3] +int TreeItem::childCount() const +{ + return childItems.count(); +} +//! [3] + +//! [4] +int TreeItem::childNumber() const +{ + if (parentItem) + return parentItem->childItems.indexOf(const_cast(this)); + + return 0; +} +//! [4] + +//! [5] +int TreeItem::columnCount() const +{ + return itemData.count(); +} +//! [5] + +//! [6] +QVariant TreeItem::data(int column) const +{ + return itemData.value(column); +} +//! [6] + +//! [7] +bool TreeItem::insertChildren(int position, int count, int columns) +{ + if (position < 0 || position > childItems.size()) + return false; + + for (int row = 0; row < count; ++row) { + QVector data(columns); + TreeItem *item = new TreeItem(data, this); + childItems.insert(position, item); + } + + return true; +} +//! [7] + +//! [8] +bool TreeItem::insertColumns(int position, int columns) +{ + if (position < 0 || position > itemData.size()) + return false; + + for (int column = 0; column < columns; ++column) + itemData.insert(position, QVariant()); + + foreach (TreeItem *child, childItems) + child->insertColumns(position, columns); + + return true; +} +//! [8] + +//! [9] +TreeItem *TreeItem::parent() +{ + return parentItem; +} +//! [9] + +//! [10] +bool TreeItem::removeChildren(int position, int count) +{ + if (position < 0 || position + count > childItems.size()) + return false; + + for (int row = 0; row < count; ++row) + delete childItems.takeAt(position); + + return true; +} +//! [10] + +bool TreeItem::removeColumns(int position, int columns) +{ + if (position < 0 || position + columns > itemData.size()) + return false; + + for (int column = 0; column < columns; ++column) + itemData.remove(position); + + foreach (TreeItem *child, childItems) + child->removeColumns(position, columns); + + return true; +} + +//! [11] +bool TreeItem::setData(int column, const QVariant &value) +{ + if (column < 0 || column >= itemData.size()) + return false; + + itemData[column] = value; + return true; +} +//! [11] diff --git a/examples/widgets/itemviews/editabletreemodel/treeitem.h b/examples/widgets/itemviews/editabletreemodel/treeitem.h new file mode 100644 index 0000000000..8426514759 --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/treeitem.h @@ -0,0 +1,74 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TREEITEM_H +#define TREEITEM_H + +#include +#include +#include + +//! [0] +class TreeItem +{ +public: + TreeItem(const QVector &data, TreeItem *parent = 0); + ~TreeItem(); + + TreeItem *child(int number); + int childCount() const; + int columnCount() const; + QVariant data(int column) const; + bool insertChildren(int position, int count, int columns); + bool insertColumns(int position, int columns); + TreeItem *parent(); + bool removeChildren(int position, int count); + bool removeColumns(int position, int columns); + int childNumber() const; + bool setData(int column, const QVariant &value); + +private: + QList childItems; + QVector itemData; + TreeItem *parentItem; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp new file mode 100644 index 0000000000..8192c14e9f --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp @@ -0,0 +1,288 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "treeitem.h" +#include "treemodel.h" + +//! [0] +TreeModel::TreeModel(const QStringList &headers, const QString &data, + QObject *parent) + : QAbstractItemModel(parent) +{ + QVector rootData; + foreach (QString header, headers) + rootData << header; + + rootItem = new TreeItem(rootData); + setupModelData(data.split(QString("\n")), rootItem); +} +//! [0] + +//! [1] +TreeModel::~TreeModel() +{ + delete rootItem; +} +//! [1] + +//! [2] +int TreeModel::columnCount(const QModelIndex & /* parent */) const +{ + return rootItem->columnCount(); +} +//! [2] + +QVariant TreeModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (role != Qt::DisplayRole && role != Qt::EditRole) + return QVariant(); + + TreeItem *item = getItem(index); + + return item->data(index.column()); +} + +//! [3] +Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return 0; + + return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; +} +//! [3] + +//! [4] +TreeItem *TreeModel::getItem(const QModelIndex &index) const +{ + if (index.isValid()) { + TreeItem *item = static_cast(index.internalPointer()); + if (item) return item; + } + return rootItem; +} +//! [4] + +QVariant TreeModel::headerData(int section, Qt::Orientation orientation, + int role) const +{ + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) + return rootItem->data(section); + + return QVariant(); +} + +//! [5] +QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const +{ + if (parent.isValid() && parent.column() != 0) + return QModelIndex(); +//! [5] + +//! [6] + TreeItem *parentItem = getItem(parent); + + TreeItem *childItem = parentItem->child(row); + if (childItem) + return createIndex(row, column, childItem); + else + return QModelIndex(); +} +//! [6] + +bool TreeModel::insertColumns(int position, int columns, const QModelIndex &parent) +{ + bool success; + + beginInsertColumns(parent, position, position + columns - 1); + success = rootItem->insertColumns(position, columns); + endInsertColumns(); + + return success; +} + +bool TreeModel::insertRows(int position, int rows, const QModelIndex &parent) +{ + TreeItem *parentItem = getItem(parent); + bool success; + + beginInsertRows(parent, position, position + rows - 1); + success = parentItem->insertChildren(position, rows, rootItem->columnCount()); + endInsertRows(); + + return success; +} + +//! [7] +QModelIndex TreeModel::parent(const QModelIndex &index) const +{ + if (!index.isValid()) + return QModelIndex(); + + TreeItem *childItem = getItem(index); + TreeItem *parentItem = childItem->parent(); + + if (parentItem == rootItem) + return QModelIndex(); + + return createIndex(parentItem->childNumber(), 0, parentItem); +} +//! [7] + +bool TreeModel::removeColumns(int position, int columns, const QModelIndex &parent) +{ + bool success; + + beginRemoveColumns(parent, position, position + columns - 1); + success = rootItem->removeColumns(position, columns); + endRemoveColumns(); + + if (rootItem->columnCount() == 0) + removeRows(0, rowCount()); + + return success; +} + +bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent) +{ + TreeItem *parentItem = getItem(parent); + bool success = true; + + beginRemoveRows(parent, position, position + rows - 1); + success = parentItem->removeChildren(position, rows); + endRemoveRows(); + + return success; +} + +//! [8] +int TreeModel::rowCount(const QModelIndex &parent) const +{ + TreeItem *parentItem = getItem(parent); + + return parentItem->childCount(); +} +//! [8] + +bool TreeModel::setData(const QModelIndex &index, const QVariant &value, + int role) +{ + if (role != Qt::EditRole) + return false; + + TreeItem *item = getItem(index); + bool result = item->setData(index.column(), value); + + if (result) + emit dataChanged(index, index); + + return result; +} + +bool TreeModel::setHeaderData(int section, Qt::Orientation orientation, + const QVariant &value, int role) +{ + if (role != Qt::EditRole || orientation != Qt::Horizontal) + return false; + + bool result = rootItem->setData(section, value); + + if (result) + emit headerDataChanged(orientation, section, section); + + return result; +} + +void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) +{ + QList parents; + QList indentations; + parents << parent; + indentations << 0; + + int number = 0; + + while (number < lines.count()) { + int position = 0; + while (position < lines[number].length()) { + if (lines[number].mid(position, 1) != " ") + break; + position++; + } + + QString lineData = lines[number].mid(position).trimmed(); + + if (!lineData.isEmpty()) { + // Read the column data from the rest of the line. + QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); + QVector columnData; + for (int column = 0; column < columnStrings.count(); ++column) + columnData << columnStrings[column]; + + if (position > indentations.last()) { + // The last child of the current parent is now the new parent + // unless the current parent has no children. + + if (parents.last()->childCount() > 0) { + parents << parents.last()->child(parents.last()->childCount()-1); + indentations << position; + } + } else { + while (position < indentations.last() && parents.count() > 0) { + parents.pop_back(); + indentations.pop_back(); + } + } + + // Append a new item to the current parent's list of children. + TreeItem *parent = parents.last(); + parent->insertChildren(parent->childCount(), 1, rootItem->columnCount()); + for (int column = 0; column < columnData.size(); ++column) + parent->child(parent->childCount() - 1)->setData(column, columnData[column]); + } + + number++; + } +} diff --git a/examples/widgets/itemviews/editabletreemodel/treemodel.h b/examples/widgets/itemviews/editabletreemodel/treemodel.h new file mode 100644 index 0000000000..f124df2e1d --- /dev/null +++ b/examples/widgets/itemviews/editabletreemodel/treemodel.h @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TREEMODEL_H +#define TREEMODEL_H + +#include +#include +#include + +class TreeItem; + +//! [0] +class TreeModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + TreeModel(const QStringList &headers, const QString &data, + QObject *parent = 0); + ~TreeModel(); +//! [0] //! [1] + + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const; + + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; +//! [1] + +//! [2] + Qt::ItemFlags flags(const QModelIndex &index) const; + bool setData(const QModelIndex &index, const QVariant &value, + int role = Qt::EditRole); + bool setHeaderData(int section, Qt::Orientation orientation, + const QVariant &value, int role = Qt::EditRole); + + bool insertColumns(int position, int columns, + const QModelIndex &parent = QModelIndex()); + bool removeColumns(int position, int columns, + const QModelIndex &parent = QModelIndex()); + bool insertRows(int position, int rows, + const QModelIndex &parent = QModelIndex()); + bool removeRows(int position, int rows, + const QModelIndex &parent = QModelIndex()); + +private: + void setupModelData(const QStringList &lines, TreeItem *parent); + TreeItem *getItem(const QModelIndex &index) const; + + TreeItem *rootItem; +}; +//! [2] + +#endif diff --git a/examples/widgets/itemviews/fetchmore/fetchmore.desktop b/examples/widgets/itemviews/fetchmore/fetchmore.desktop new file mode 100644 index 0000000000..b8c9ff32cb --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/fetchmore.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Fetch More +Exec=/opt/usr/bin/fetchmore +Icon=fetchmore +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/fetchmore/fetchmore.pro b/examples/widgets/itemviews/fetchmore/fetchmore.pro new file mode 100644 index 0000000000..28af7e9ac0 --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/fetchmore.pro @@ -0,0 +1,13 @@ +HEADERS = filelistmodel.h \ + window.h +SOURCES = filelistmodel.cpp \ + main.cpp \ + window.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/fetchmore +sources.files = $$SOURCES $$HEADERS *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/fetchmore +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/fetchmore/filelistmodel.cpp b/examples/widgets/itemviews/fetchmore/filelistmodel.cpp new file mode 100644 index 0000000000..d9678191d9 --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/filelistmodel.cpp @@ -0,0 +1,116 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "filelistmodel.h" +#include +#include +#include +#include + +FileListModel::FileListModel(QObject *parent) + : QAbstractListModel(parent) +{ +} + +//![4] +int FileListModel::rowCount(const QModelIndex & /* parent */) const +{ + return fileCount; +} + +QVariant FileListModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (index.row() >= fileList.size() || index.row() < 0) + return QVariant(); + + if (role == Qt::DisplayRole) + return fileList.at(index.row()); + else if (role == Qt::BackgroundRole) { + int batch = (index.row() / 100) % 2; + if (batch == 0) + return qApp->palette().base(); + else + return qApp->palette().alternateBase(); + } + return QVariant(); +} +//![4] + +//![1] +bool FileListModel::canFetchMore(const QModelIndex & /* index */) const +{ + if (fileCount < fileList.size()) + return true; + else + return false; +} +//![1] + +//![2] +void FileListModel::fetchMore(const QModelIndex & /* index */) +{ + int remainder = fileList.size() - fileCount; + int itemsToFetch = qMin(100, remainder); + + beginInsertRows(QModelIndex(), fileCount, fileCount+itemsToFetch-1); + + fileCount += itemsToFetch; + + endInsertRows(); + + emit numberPopulated(itemsToFetch); +} +//![2] + +//![0] +void FileListModel::setDirPath(const QString &path) +{ + QDir dir(path); + + beginResetModel(); + fileList = dir.entryList(); + fileCount = 0; + endResetModel(); +} +//![0] + diff --git a/examples/widgets/itemviews/fetchmore/filelistmodel.h b/examples/widgets/itemviews/fetchmore/filelistmodel.h new file mode 100644 index 0000000000..f3e9f758c7 --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/filelistmodel.h @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef FILELISTMODEL_H +#define FILELISTMODEL_H + +#include +#include +#include + +//![0] +class FileListModel : public QAbstractListModel +{ + Q_OBJECT + +public: + FileListModel(QObject *parent = 0); + + int rowCount(const QModelIndex &parent = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + +signals: + void numberPopulated(int number); + +public slots: + void setDirPath(const QString &path); + +protected: + bool canFetchMore(const QModelIndex &parent) const; + void fetchMore(const QModelIndex &parent); + +private: + QStringList fileList; + int fileCount; +}; +//![0] + +#endif diff --git a/examples/widgets/itemviews/fetchmore/main.cpp b/examples/widgets/itemviews/fetchmore/main.cpp new file mode 100644 index 0000000000..97b94d1d3c --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/main.cpp @@ -0,0 +1,50 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "window.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Window window; + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/fetchmore/window.cpp b/examples/widgets/itemviews/fetchmore/window.cpp new file mode 100644 index 0000000000..f138fb4bd4 --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/window.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "filelistmodel.h" +#include "window.h" + +Window::Window(QWidget *parent) + : QWidget(parent) +{ + FileListModel *model = new FileListModel(this); + model->setDirPath(QLibraryInfo::location(QLibraryInfo::PrefixPath)); + + QLabel *label = new QLabel(tr("&Directory:")); + QLineEdit *lineEdit = new QLineEdit; + label->setBuddy(lineEdit); + + QListView *view = new QListView; + view->setModel(model); + + logViewer = new QTextBrowser; + logViewer->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); + + connect(lineEdit, SIGNAL(textChanged(QString)), + model, SLOT(setDirPath(QString))); + connect(lineEdit, SIGNAL(textChanged(QString)), + logViewer, SLOT(clear())); + connect(model, SIGNAL(numberPopulated(int)), + this, SLOT(updateLog(int))); + + QGridLayout *layout = new QGridLayout; + layout->addWidget(label, 0, 0); + layout->addWidget(lineEdit, 0, 1); + layout->addWidget(view, 1, 0, 1, 2); + layout->addWidget(logViewer, 2, 0, 1, 2); + + setLayout(layout); + setWindowTitle(tr("Fetch More Example")); +} + +void Window::updateLog(int number) +{ + logViewer->append(tr("%1 items added.").arg(number)); +} diff --git a/examples/widgets/itemviews/fetchmore/window.h b/examples/widgets/itemviews/fetchmore/window.h new file mode 100644 index 0000000000..cf6208b643 --- /dev/null +++ b/examples/widgets/itemviews/fetchmore/window.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include + +QT_BEGIN_NAMESPACE +class QTextBrowser; +QT_END_NAMESPACE + +class Window : public QWidget +{ + Q_OBJECT + +public: + Window(QWidget *parent = 0); + +public slots: + void updateLog(int number); + +private: + QTextBrowser *logViewer; +}; + +#endif diff --git a/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp b/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp new file mode 100644 index 0000000000..ae83c341c4 --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/freezetablewidget.cpp @@ -0,0 +1,165 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "freezetablewidget.h" + +//! [constructor] +FreezeTableWidget::FreezeTableWidget(QAbstractItemModel * model) +{ + setModel(model); + frozenTableView = new QTableView(this); + + init(); + + //connect the headers and scrollbars of both tableviews together + connect(horizontalHeader(),SIGNAL(sectionResized(int,int,int)), this, + SLOT(updateSectionWidth(int,int,int))); + connect(verticalHeader(),SIGNAL(sectionResized(int,int,int)), this, + SLOT(updateSectionHeight(int,int,int))); + + connect(frozenTableView->verticalScrollBar(), SIGNAL(valueChanged(int)), + verticalScrollBar(), SLOT(setValue(int))); + connect(verticalScrollBar(), SIGNAL(valueChanged(int)), + frozenTableView->verticalScrollBar(), SLOT(setValue(int))); + + +} +//! [constructor] + +FreezeTableWidget::~FreezeTableWidget() +{ + delete frozenTableView; +} + +//! [init part1] +void FreezeTableWidget::init() +{ + frozenTableView->setModel(model()); + frozenTableView->setFocusPolicy(Qt::NoFocus); + frozenTableView->verticalHeader()->hide(); + frozenTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); + + viewport()->stackUnder(frozenTableView); +//! [init part1] + +//! [init part2] + frozenTableView->setStyleSheet("QTableView { border: none;" + "background-color: #8EDE21;" + "selection-background-color: #999}"); //for demo purposes + frozenTableView->setSelectionModel(selectionModel()); + for(int col=1; colcolumnCount(); col++) + frozenTableView->setColumnHidden(col, true); + + frozenTableView->setColumnWidth(0, columnWidth(0) ); + + frozenTableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + frozenTableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + frozenTableView->show(); + + updateFrozenTableGeometry(); + + setHorizontalScrollMode(ScrollPerPixel); + setVerticalScrollMode(ScrollPerPixel); + frozenTableView->setVerticalScrollMode(ScrollPerPixel); +} +//! [init part2] + + +//! [sections] +void FreezeTableWidget::updateSectionWidth(int logicalIndex, int, int newSize) +{ + if(logicalIndex==0){ + frozenTableView->setColumnWidth(0,newSize); + updateFrozenTableGeometry(); + } +} + +void FreezeTableWidget::updateSectionHeight(int logicalIndex, int, int newSize) +{ + frozenTableView->setRowHeight(logicalIndex, newSize); +} +//! [sections] + + +//! [resize] +void FreezeTableWidget::resizeEvent(QResizeEvent * event) +{ + QTableView::resizeEvent(event); + updateFrozenTableGeometry(); + } +//! [resize] + + +//! [navigate] +QModelIndex FreezeTableWidget::moveCursor(CursorAction cursorAction, + Qt::KeyboardModifiers modifiers) +{ + QModelIndex current = QTableView::moveCursor(cursorAction, modifiers); + + if(cursorAction == MoveLeft && current.column()>0 + && visualRect(current).topLeft().x() < frozenTableView->columnWidth(0) ){ + + const int newValue = horizontalScrollBar()->value() + visualRect(current).topLeft().x() + - frozenTableView->columnWidth(0); + horizontalScrollBar()->setValue(newValue); + } + return current; +} +//! [navigate] + +void FreezeTableWidget::scrollTo (const QModelIndex & index, ScrollHint hint){ + if(index.column()>0) + QTableView::scrollTo(index, hint); +} + + + +//! [geometry] +void FreezeTableWidget::updateFrozenTableGeometry() +{ + frozenTableView->setGeometry( verticalHeader()->width()+frameWidth(), + frameWidth(), columnWidth(0), + viewport()->height()+horizontalHeader()->height()); +} +//! [geometry] + + diff --git a/examples/widgets/itemviews/frozencolumn/freezetablewidget.h b/examples/widgets/itemviews/frozencolumn/freezetablewidget.h new file mode 100644 index 0000000000..1432c012f5 --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/freezetablewidget.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef FREEZETABLEWIDGET_H +#define FREEZETABLEWIDGET_H + +#include + +//! [Widget definition] +class FreezeTableWidget : public QTableView { + Q_OBJECT + +public: + FreezeTableWidget(QAbstractItemModel * model); + ~FreezeTableWidget(); + + +protected: + virtual void resizeEvent(QResizeEvent *event); + virtual QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers); + void scrollTo (const QModelIndex & index, ScrollHint hint = EnsureVisible); + +private: + QTableView *frozenTableView; + void init(); + void updateFrozenTableGeometry(); + + +private slots: + void updateSectionWidth(int logicalIndex,int, int newSize); + void updateSectionHeight(int logicalIndex, int, int newSize); + +}; +//! [Widget definition] +#endif diff --git a/examples/widgets/itemviews/frozencolumn/frozencolumn.desktop b/examples/widgets/itemviews/frozencolumn/frozencolumn.desktop new file mode 100644 index 0000000000..3d1e3b430d --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/frozencolumn.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Frozen Column +Exec=/opt/usr/bin/frozencolumn +Icon=frozencolumn +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/frozencolumn/frozencolumn.pro b/examples/widgets/itemviews/frozencolumn/frozencolumn.pro new file mode 100644 index 0000000000..34a4a4de8c --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/frozencolumn.pro @@ -0,0 +1,11 @@ +HEADERS += freezetablewidget.h +SOURCES += main.cpp freezetablewidget.cpp +RESOURCES += grades.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/frozencolumn +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/frozencolumn +INSTALLS += target sources +QT += widgets + diff --git a/examples/widgets/itemviews/frozencolumn/grades.qrc b/examples/widgets/itemviews/frozencolumn/grades.qrc new file mode 100644 index 0000000000..5f16d56931 --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/grades.qrc @@ -0,0 +1,5 @@ + + + grades.txt + + diff --git a/examples/widgets/itemviews/frozencolumn/grades.txt b/examples/widgets/itemviews/frozencolumn/grades.txt new file mode 100644 index 0000000000..e1c6fcc49e --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/grades.txt @@ -0,0 +1,36 @@ + France , Norway , YDS , UK(tech.), UK(adj.) , UIAA , Ger , Australia , Finland , Brazil + +1, , 5.2, , , I , I , , , Isup +2, , 5.3, , , II , II , 11, , II +3, 3, 5.4, , , III , III , 12, , IIsup +4, 4, 5.5, 4a , VD , IV , IV , 12, , III +5a , 5-, 5.6, , S , V- , V , 13, 5-, IIIsup +5b , 5, 5.7, 4b , HS , V , VI , 14, 5, IV + , , , 4c , , V+ , , 15, , +5c , 5+, 5.8, , VS , VI- , VIIa , 16, 5, IVsup +6a , 6-, 5.9, 5a , HVS , VI , VIIb , 17, , V +6a+ , 6-/6 , 5.10a , , E1 , VI+ , VIIc , 18, 6-, VI +6b , , 5.10b , 5b , , , , 19, , VI/VI+ +6b+ , 6, 5.10c , , E2 , VII- , VIIIa , 20, 6, VIsup/VI+ +6c , 6+, 5.10d , 5c , , VII , VIIIb , 21, , VIsup +6c+ , 7-, 5.11a , , E3 , VII+ , VIIIc , 22, 6, 7a +6c+ , 7, 5.11b , , , , , 23, , 7b +7a , 7+, 5.11c , 6a , E4 , VIII- , IXa , 24, 7-, 7c +7a , 7+/8- , 5.11d , , , VIII , IXb , , , 7c +7a+ , 8-, 5.12a , , E5 , VIII+ , IXc , 25, 7, 8a +7b , 8, 5.12b , 6b , , , , 26, 8-, 8b +7b+ , 8/8+ , 5.12c , , E6 , IX- , Xa , 27, 8, 8c +7c , 8+, 5.12d , 6c , , IX , Xb , 28, 8, 9a +7c+ , 9-, 5.13a , , E7 , IX+ , Xc , 29, 9-, 9b +8a , , 5.13b , , , , , , 9, 9c +8a+ , 9-/9 , 5.13c , 7a , , X- , , 30, 9, 10a +8b , 9, 5.13d , , E8 , X , , 31, 10-, 10b +8b+ , 9/9+ , 5.14a , , , X+ , , 32, 10, 10c +8c , 9+, 5.14b , 7b , , , , 33, 10, 11a +8c+ , 10-, 5.14c , , E9 , XI- , , 34, 11-, 11b +9a , 10, 5.14d , 7c , , XI , , 35, 11, 11c +9a+ , , 5.15a , , , XI+ , , , , 12a +9b , , 5.15b , , , , , , , 12b + +# Wikipedia contributors. Grade (climbing). Wikipedia, The Free Encyclopedia. May 15, 2009, 20:42 UTC. +# Available at: http://en.wikipedia.org/w/index.php?title=Grade_(climbing)&oldid=290165724. Accessed May 28, 2009. diff --git a/examples/widgets/itemviews/frozencolumn/main.cpp b/examples/widgets/itemviews/frozencolumn/main.cpp new file mode 100644 index 0000000000..ff50e97db9 --- /dev/null +++ b/examples/widgets/itemviews/frozencolumn/main.cpp @@ -0,0 +1,88 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include "freezetablewidget.h" + +int main( int argc, char** argv ) +{ + + Q_INIT_RESOURCE(grades); + + + QApplication app( argc, argv ); + QStandardItemModel *model=new QStandardItemModel(); + + + QFile file(":/grades.txt"); + QString line; + QStringList list; + if (file.open(QFile::ReadOnly)) { + line = file.readLine(200); + list= line.simplified().split(","); + model->setHorizontalHeaderLabels(list); + + int row=0; + QStandardItem *newItem=0; + while(file.canReadLine()){ + line = file.readLine(200); + if(!line.startsWith("#") && line.contains(",")){ + list= line.simplified().split(","); + for(int col=0; colsetItem(row ,col, newItem); + } + row++; + } + } + } + file.close(); + + FreezeTableWidget *tableView = new FreezeTableWidget(model); + + tableView->setWindowTitle(QObject::tr("Frozen Column Example")); + tableView->resize(560,680); + tableView->show(); + return app.exec(); +} + diff --git a/examples/widgets/itemviews/interview/README b/examples/widgets/itemviews/interview/README new file mode 100644 index 0000000000..50894428f6 --- /dev/null +++ b/examples/widgets/itemviews/interview/README @@ -0,0 +1,2 @@ +The interview example shows the same model and selection being shared +between three different views. diff --git a/examples/widgets/itemviews/interview/images/folder.png b/examples/widgets/itemviews/interview/images/folder.png new file mode 100644 index 0000000000..589fd2df59 Binary files /dev/null and b/examples/widgets/itemviews/interview/images/folder.png differ diff --git a/examples/widgets/itemviews/interview/images/interview.png b/examples/widgets/itemviews/interview/images/interview.png new file mode 100644 index 0000000000..0c3d690258 Binary files /dev/null and b/examples/widgets/itemviews/interview/images/interview.png differ diff --git a/examples/widgets/itemviews/interview/images/services.png b/examples/widgets/itemviews/interview/images/services.png new file mode 100644 index 0000000000..6b2ad969d4 Binary files /dev/null and b/examples/widgets/itemviews/interview/images/services.png differ diff --git a/examples/widgets/itemviews/interview/interview.pro b/examples/widgets/itemviews/interview/interview.pro new file mode 100644 index 0000000000..5cd0d1f9fc --- /dev/null +++ b/examples/widgets/itemviews/interview/interview.pro @@ -0,0 +1,19 @@ +TEMPLATE = app + +CONFIG += qt warn_on +HEADERS += model.h +SOURCES += model.cpp main.cpp +RESOURCES += interview.qrc + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/interview +sources.files = $$SOURCES $$HEADERS $$RESOURCES README *.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/interview +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/interview/interview.qrc b/examples/widgets/itemviews/interview/interview.qrc new file mode 100644 index 0000000000..b28ea34d8a --- /dev/null +++ b/examples/widgets/itemviews/interview/interview.qrc @@ -0,0 +1,7 @@ + + + images/folder.png + images/services.png + images/interview.png + + diff --git a/examples/widgets/itemviews/interview/main.cpp b/examples/widgets/itemviews/interview/main.cpp new file mode 100644 index 0000000000..fa059cdb53 --- /dev/null +++ b/examples/widgets/itemviews/interview/main.cpp @@ -0,0 +1,95 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "model.h" + +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(interview); + + QApplication app(argc, argv); + QSplitter page; + + QAbstractItemModel *data = new Model(1000, 10, &page); + QItemSelectionModel *selections = new QItemSelectionModel(data); + + QTableView *table = new QTableView; + table->setModel(data); + table->setSelectionModel(selections); + table->horizontalHeader()->setSectionsMovable(true); + table->verticalHeader()->setSectionsMovable(true); + // Set StaticContents to enable minimal repaints on resizes. + table->viewport()->setAttribute(Qt::WA_StaticContents); + page.addWidget(table); + + QTreeView *tree = new QTreeView; + tree->setModel(data); + tree->setSelectionModel(selections); + tree->setUniformRowHeights(true); + tree->header()->setStretchLastSection(false); + tree->viewport()->setAttribute(Qt::WA_StaticContents); + // Disable the focus rect to get minimal repaints when scrolling on Mac. + tree->setAttribute(Qt::WA_MacShowFocusRect, false); + page.addWidget(tree); + + QListView *list = new QListView; + list->setModel(data); + list->setSelectionModel(selections); + list->setViewMode(QListView::IconMode); + list->setSelectionMode(QAbstractItemView::ExtendedSelection); + list->setAlternatingRowColors(false); + list->viewport()->setAttribute(Qt::WA_StaticContents); + list->setAttribute(Qt::WA_MacShowFocusRect, false); + page.addWidget(list); + + page.setWindowIcon(QPixmap(":/images/interview.png")); + page.setWindowTitle("Interview"); + page.show(); + + return app.exec(); +} diff --git a/examples/widgets/itemviews/interview/model.cpp b/examples/widgets/itemviews/interview/model.cpp new file mode 100644 index 0000000000..3b20f91ed6 --- /dev/null +++ b/examples/widgets/itemviews/interview/model.cpp @@ -0,0 +1,147 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "model.h" +#include +#include + +Model::Model(int rows, int columns, QObject *parent) + : QAbstractItemModel(parent), + services(QPixmap(":/images/services.png")), + rc(rows), cc(columns), + tree(new QVector(rows, Node(0))) +{ + +} + +Model::~Model() +{ + delete tree; +} + +QModelIndex Model::index(int row, int column, const QModelIndex &parent) const +{ + if (row < rc && row >= 0 && column < cc && column >= 0) { + Node *p = static_cast(parent.internalPointer()); + Node *n = node(row, p); + if (n) + return createIndex(row, column, n); + } + return QModelIndex(); +} + +QModelIndex Model::parent(const QModelIndex &child) const +{ + if (child.isValid()) { + Node *n = static_cast(child.internalPointer()); + Node *p = parent(n); + if (p) + return createIndex(row(p), 0, p); + } + return QModelIndex(); +} + +int Model::rowCount(const QModelIndex &parent) const +{ + return (parent.isValid() && parent.column() != 0) ? 0 : rc; +} + +int Model::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return cc; +} + +QVariant Model::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + if (role == Qt::DisplayRole) + return QVariant("Item " + QString::number(index.row()) + ":" + QString::number(index.column())); + if (role == Qt::DecorationRole) { + if (index.column() == 0) + return iconProvider.icon(QFileIconProvider::Folder); + return iconProvider.icon(QFileIconProvider::File); + } + return QVariant(); +} + +QVariant Model::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (role == Qt::DisplayRole) + return QString::number(section); + if (role == Qt::DecorationRole) + return QVariant::fromValue(services); + return QAbstractItemModel::headerData(section, orientation, role); +} + +bool Model::hasChildren(const QModelIndex &parent) const +{ + if (parent.isValid() && parent.column() != 0) + return false; + return rc > 0 && cc > 0; +} + +Qt::ItemFlags Model::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return 0; + return (Qt::ItemIsDragEnabled|Qt::ItemIsSelectable|Qt::ItemIsEnabled); +} + +Model::Node *Model::node(int row, Node *parent) const +{ + if (parent && !parent->children) + parent->children = new QVector(rc, Node(parent)); + QVector *v = parent ? parent->children : tree; + return const_cast(&(v->at(row))); +} + +Model::Node *Model::parent(Node *child) const +{ + return child ? child->parent : 0; +} + +int Model::row(Node *node) const +{ + const Node *first = node->parent ? &(node->parent->children->at(0)) : &(tree->at(0)); + return (node - first); +} diff --git a/examples/widgets/itemviews/interview/model.h b/examples/widgets/itemviews/interview/model.h new file mode 100644 index 0000000000..0480ce1763 --- /dev/null +++ b/examples/widgets/itemviews/interview/model.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MODEL_H +#define MODEL_H + +#include +#include +#include +#include + +class Model : public QAbstractItemModel +{ + Q_OBJECT + +public: + Model(int rows, int columns, QObject *parent = 0); + ~Model(); + + QModelIndex index(int row, int column, const QModelIndex &parent) const; + QModelIndex parent(const QModelIndex &child) const; + + int rowCount(const QModelIndex &parent) const; + int columnCount(const QModelIndex &parent) const; + + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role) const; + + bool hasChildren(const QModelIndex &parent) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + +private: + + struct Node + { + Node(Node *parent = 0) : parent(parent), children(0) {} + ~Node() { delete children; } + Node *parent; + QVector *children; + }; + + Node *node(int row, Node *parent) const; + Node *parent(Node *child) const; + int row(Node *node) const; + + QIcon services; + int rc, cc; + QVector *tree; + QFileIconProvider iconProvider; +}; + +#endif diff --git a/examples/widgets/itemviews/itemviews.pro b/examples/widgets/itemviews/itemviews.pro new file mode 100644 index 0000000000..347c259bc2 --- /dev/null +++ b/examples/widgets/itemviews/itemviews.pro @@ -0,0 +1,25 @@ +TEMPLATE = subdirs +SUBDIRS = addressbook \ + basicsortfiltermodel \ + chart \ + combowidgetmapper \ + customsortfiltermodel \ + dirview \ + editabletreemodel \ + fetchmore \ + frozencolumn \ + interview \ + pixelator \ + puzzle \ + simpledommodel \ + simpletreemodel \ + simplewidgetmapper \ + spinboxdelegate \ + spreadsheet + +# install +sources.files = README *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews +INSTALLS += sources + +QT += widgets diff --git a/examples/widgets/itemviews/pixelator/imagemodel.cpp b/examples/widgets/itemviews/pixelator/imagemodel.cpp new file mode 100644 index 0000000000..efbf2d35bc --- /dev/null +++ b/examples/widgets/itemviews/pixelator/imagemodel.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "imagemodel.h" + +//! [0] +ImageModel::ImageModel(QObject *parent) + : QAbstractTableModel(parent) +{ +} +//! [0] + +//! [1] +void ImageModel::setImage(const QImage &image) +{ + beginResetModel(); + modelImage = image; + endResetModel(); +} +//! [1] + +//! [2] +int ImageModel::rowCount(const QModelIndex & /* parent */) const +{ + return modelImage.height(); +} + +int ImageModel::columnCount(const QModelIndex & /* parent */) const +//! [2] //! [3] +{ + return modelImage.width(); +} +//! [3] + +//! [4] +QVariant ImageModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || role != Qt::DisplayRole) + return QVariant(); + return qGray(modelImage.pixel(index.column(), index.row())); +} +//! [4] + +//! [5] +QVariant ImageModel::headerData(int /* section */, + Qt::Orientation /* orientation */, + int role) const +{ + if (role == Qt::SizeHintRole) + return QSize(1, 1); + return QVariant(); +} +//! [5] diff --git a/examples/widgets/itemviews/pixelator/imagemodel.h b/examples/widgets/itemviews/pixelator/imagemodel.h new file mode 100644 index 0000000000..2f778ca927 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/imagemodel.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef IMAGEMODEL_H +#define IMAGEMODEL_H + +#include +#include + +//! [0] +class ImageModel : public QAbstractTableModel +{ + Q_OBJECT + +public: + ImageModel(QObject *parent = 0); + + void setImage(const QImage &image); + + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; + + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + +private: + QImage modelImage; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/pixelator/images.qrc b/examples/widgets/itemviews/pixelator/images.qrc new file mode 100644 index 0000000000..c105e13895 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/images.qrc @@ -0,0 +1,5 @@ + + + images/qt.png + + diff --git a/examples/widgets/itemviews/pixelator/images/qt.png b/examples/widgets/itemviews/pixelator/images/qt.png new file mode 100644 index 0000000000..a2c9c77c16 Binary files /dev/null and b/examples/widgets/itemviews/pixelator/images/qt.png differ diff --git a/examples/widgets/itemviews/pixelator/main.cpp b/examples/widgets/itemviews/pixelator/main.cpp new file mode 100644 index 0000000000..e877051775 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/main.cpp @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(images); + + QApplication app(argc, argv); + MainWindow window; + window.show(); + window.openImage(":/images/qt.png"); + return app.exec(); +} diff --git a/examples/widgets/itemviews/pixelator/mainwindow.cpp b/examples/widgets/itemviews/pixelator/mainwindow.cpp new file mode 100644 index 0000000000..20dfba18f4 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/mainwindow.cpp @@ -0,0 +1,248 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#ifndef QT_NO_PRINTER +#include +#include +#endif + +#include "imagemodel.h" +#include "mainwindow.h" +#include "pixeldelegate.h" + +//! [0] +MainWindow::MainWindow() +{ +//! [0] + currentPath = QDir::homePath(); + model = new ImageModel(this); + + QWidget *centralWidget = new QWidget; + +//! [1] + view = new QTableView; + view->setShowGrid(false); + view->horizontalHeader()->hide(); + view->verticalHeader()->hide(); + view->horizontalHeader()->setMinimumSectionSize(1); + view->verticalHeader()->setMinimumSectionSize(1); + view->setModel(model); +//! [1] + +//! [2] + PixelDelegate *delegate = new PixelDelegate(this); + view->setItemDelegate(delegate); +//! [2] + +//! [3] + QLabel *pixelSizeLabel = new QLabel(tr("Pixel size:")); + QSpinBox *pixelSizeSpinBox = new QSpinBox; + pixelSizeSpinBox->setMinimum(4); + pixelSizeSpinBox->setMaximum(32); + pixelSizeSpinBox->setValue(12); +//! [3] + + QMenu *fileMenu = new QMenu(tr("&File"), this); + QAction *openAction = fileMenu->addAction(tr("&Open...")); + openAction->setShortcuts(QKeySequence::Open); + + printAction = fileMenu->addAction(tr("&Print...")); + printAction->setEnabled(false); + printAction->setShortcut(QKeySequence::Print); + + QAction *quitAction = fileMenu->addAction(tr("E&xit")); + quitAction->setShortcuts(QKeySequence::Quit); + + QMenu *helpMenu = new QMenu(tr("&Help"), this); + QAction *aboutAction = helpMenu->addAction(tr("&About")); + + menuBar()->addMenu(fileMenu); + menuBar()->addSeparator(); + menuBar()->addMenu(helpMenu); + + connect(openAction, SIGNAL(triggered()), this, SLOT(chooseImage())); + connect(printAction, SIGNAL(triggered()), this, SLOT(printImage())); + connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + connect(aboutAction, SIGNAL(triggered()), this, SLOT(showAboutBox())); +//! [4] + connect(pixelSizeSpinBox, SIGNAL(valueChanged(int)), + delegate, SLOT(setPixelSize(int))); + connect(pixelSizeSpinBox, SIGNAL(valueChanged(int)), + this, SLOT(updateView())); +//! [4] + + QHBoxLayout *controlsLayout = new QHBoxLayout; + controlsLayout->addWidget(pixelSizeLabel); + controlsLayout->addWidget(pixelSizeSpinBox); + controlsLayout->addStretch(1); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(view); + mainLayout->addLayout(controlsLayout); + centralWidget->setLayout(mainLayout); + + setCentralWidget(centralWidget); + + setWindowTitle(tr("Pixelator")); + resize(640, 480); +//! [5] +} +//! [5] + +void MainWindow::chooseImage() +{ + QString fileName = QFileDialog::getOpenFileName(this, + tr("Choose an image"), currentPath, "*"); + + if (!fileName.isEmpty()) + openImage(fileName); +} + +void MainWindow::openImage(const QString &fileName) +{ + QImage image; + + if (image.load(fileName)) { + model->setImage(image); + if (!fileName.startsWith(":/")) { + currentPath = fileName; + setWindowTitle(tr("%1 - Pixelator").arg(currentPath)); + } + + printAction->setEnabled(true); + updateView(); + } +} + +void MainWindow::printImage() +{ +#ifndef QT_NO_PRINTER + if (model->rowCount(QModelIndex())*model->columnCount(QModelIndex()) + > 90000) { + QMessageBox::StandardButton answer; + answer = QMessageBox::question(this, tr("Large Image Size"), + tr("The printed image may be very large. Are you sure that " + "you want to print it?"), + QMessageBox::Yes | QMessageBox::No); + if (answer == QMessageBox::No) + return; + } + + QPrinter printer(QPrinter::HighResolution); + + QPrintDialog *dlg = new QPrintDialog(&printer, this); + dlg->setWindowTitle(tr("Print Image")); + + if (dlg->exec() != QDialog::Accepted) + return; + + QPainter painter; + painter.begin(&printer); + + int rows = model->rowCount(QModelIndex()); + int columns = model->columnCount(QModelIndex()); + int sourceWidth = (columns+1) * ItemSize; + int sourceHeight = (rows+1) * ItemSize; + + painter.save(); + + double xscale = printer.pageRect().width()/double(sourceWidth); + double yscale = printer.pageRect().height()/double(sourceHeight); + double scale = qMin(xscale, yscale); + + painter.translate(printer.paperRect().x() + printer.pageRect().width()/2, + printer.paperRect().y() + printer.pageRect().height()/2); + painter.scale(scale, scale); + painter.translate(-sourceWidth/2, -sourceHeight/2); + + QStyleOptionViewItem option; + QModelIndex parent = QModelIndex(); + + QProgressDialog progress(tr("Printing..."), tr("Cancel"), 0, rows, this); + progress.setWindowModality(Qt::ApplicationModal); + float y = ItemSize/2; + + for (int row = 0; row < rows; ++row) { + progress.setValue(row); + qApp->processEvents(); + if (progress.wasCanceled()) + break; + + float x = ItemSize/2; + + for (int column = 0; column < columns; ++column) { + option.rect = QRect(int(x), int(y), ItemSize, ItemSize); + view->itemDelegate()->paint(&painter, option, + model->index(row, column, parent)); + x = x + ItemSize; + } + y = y + ItemSize; + } + progress.setValue(rows); + + painter.restore(); + painter.end(); + + if (progress.wasCanceled()) { + QMessageBox::information(this, tr("Printing canceled"), + tr("The printing process was canceled."), QMessageBox::Cancel); + } +#else + QMessageBox::information(this, tr("Printing canceled"), + tr("Printing is not supported on this Qt build"), QMessageBox::Cancel); +#endif +} + +void MainWindow::showAboutBox() +{ + QMessageBox::about(this, tr("About the Pixelator example"), + tr("This example demonstrates how a standard view and a custom\n" + "delegate can be used to produce a specialized representation\n" + "of data in a simple custom model.")); +} + +//! [6] +void MainWindow::updateView() +{ + view->resizeColumnsToContents(); + view->resizeRowsToContents(); +} +//! [6] diff --git a/examples/widgets/itemviews/pixelator/mainwindow.h b/examples/widgets/itemviews/pixelator/mainwindow.h new file mode 100644 index 0000000000..1aea1f9807 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/mainwindow.h @@ -0,0 +1,74 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +class ImageModel; +QT_BEGIN_NAMESPACE +class QAction; +class QTableView; +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(); + + void openImage(const QString &fileName); + +public slots: + void chooseImage(); + void printImage(); + void showAboutBox(); + void updateView(); + +private: + ImageModel *model; + QAction *printAction; + QString currentPath; + QTableView *view; +}; + +#endif diff --git a/examples/widgets/itemviews/pixelator/pixelator.desktop b/examples/widgets/itemviews/pixelator/pixelator.desktop new file mode 100644 index 0000000000..751deb13b3 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/pixelator.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Pixelator +Exec=/opt/usr/bin/pixelator +Icon=pixelator +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/pixelator/pixelator.pro b/examples/widgets/itemviews/pixelator/pixelator.pro new file mode 100644 index 0000000000..48f8a58a58 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/pixelator.pro @@ -0,0 +1,17 @@ +HEADERS = imagemodel.h \ + mainwindow.h \ + pixeldelegate.h +SOURCES = imagemodel.cpp \ + main.cpp \ + mainwindow.cpp \ + pixeldelegate.cpp +RESOURCES += images.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/pixelator +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/pixelator +INSTALLS += target sources + +QT += widgets +!isEmpty(QT.printsupport.name): QT += printsupport diff --git a/examples/widgets/itemviews/pixelator/pixeldelegate.cpp b/examples/widgets/itemviews/pixelator/pixeldelegate.cpp new file mode 100644 index 0000000000..5904c2e680 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/pixeldelegate.cpp @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "pixeldelegate.h" + +//! [0] +PixelDelegate::PixelDelegate(QObject *parent) + : QAbstractItemDelegate(parent) +{ + pixelSize = 12; +} +//! [0] + +//! [1] +void PixelDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ +//! [2] + if (option.state & QStyle::State_Selected) + painter->fillRect(option.rect, option.palette.highlight()); +//! [1] + +//! [3] + int size = qMin(option.rect.width(), option.rect.height()); +//! [3] //! [4] + int brightness = index.model()->data(index, Qt::DisplayRole).toInt(); + double radius = (size/2.0) - (brightness/255.0 * size/2.0); + if (radius == 0.0) + return; +//! [4] + +//! [5] + painter->save(); +//! [5] //! [6] + painter->setRenderHint(QPainter::Antialiasing, true); +//! [6] //! [7] + painter->setPen(Qt::NoPen); +//! [7] //! [8] + if (option.state & QStyle::State_Selected) +//! [8] //! [9] + painter->setBrush(option.palette.highlightedText()); + else +//! [2] + painter->setBrush(option.palette.text()); +//! [9] + +//! [10] + painter->drawEllipse(QRectF(option.rect.x() + option.rect.width()/2 - radius, + option.rect.y() + option.rect.height()/2 - radius, + 2*radius, 2*radius)); + painter->restore(); +} +//! [10] + +//! [11] +QSize PixelDelegate::sizeHint(const QStyleOptionViewItem & /* option */, + const QModelIndex & /* index */) const +{ + return QSize(pixelSize, pixelSize); +} +//! [11] + +//! [12] +void PixelDelegate::setPixelSize(int size) +{ + pixelSize = size; +} +//! [12] diff --git a/examples/widgets/itemviews/pixelator/pixeldelegate.h b/examples/widgets/itemviews/pixelator/pixeldelegate.h new file mode 100644 index 0000000000..4035bc4571 --- /dev/null +++ b/examples/widgets/itemviews/pixelator/pixeldelegate.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PIXELDELEGATE_H +#define PIXELDELEGATE_H + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE +class QAbstractItemModel; +class QObject; +class QPainter; +QT_END_NAMESPACE + +static const int ItemSize = 256; + +//! [0] +class PixelDelegate : public QAbstractItemDelegate +{ + Q_OBJECT + +public: + PixelDelegate(QObject *parent = 0); + + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + + QSize sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index ) const; + +public slots: + void setPixelSize(int size); + +private: + int pixelSize; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/puzzle/example.jpg b/examples/widgets/itemviews/puzzle/example.jpg new file mode 100644 index 0000000000..e09fb70757 Binary files /dev/null and b/examples/widgets/itemviews/puzzle/example.jpg differ diff --git a/examples/widgets/itemviews/puzzle/main.cpp b/examples/widgets/itemviews/puzzle/main.cpp new file mode 100644 index 0000000000..31b7142819 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/main.cpp @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(puzzle); + + QApplication app(argc, argv); + MainWindow window; + window.openImage(":/images/example.jpg"); + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/puzzle/mainwindow.cpp b/examples/widgets/itemviews/puzzle/mainwindow.cpp new file mode 100644 index 0000000000..4b9b10946a --- /dev/null +++ b/examples/widgets/itemviews/puzzle/mainwindow.cpp @@ -0,0 +1,149 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#include "mainwindow.h" +#include "piecesmodel.h" +#include "puzzlewidget.h" + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ + setupMenus(); + setupWidgets(); + model = new PiecesModel(puzzleWidget->pieceSize(), this); + piecesList->setModel(model); + + setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); + setWindowTitle(tr("Puzzle")); +} + +void MainWindow::openImage(const QString &path) +{ + QString fileName = path; + + if (fileName.isNull()) + fileName = QFileDialog::getOpenFileName(this, + tr("Open Image"), "", tr("Image Files (*.png *.jpg *.bmp)")); + + if (!fileName.isEmpty()) { + QPixmap newImage; + if (!newImage.load(fileName)) { + QMessageBox::warning(this, tr("Open Image"), + tr("The image file could not be loaded."), + QMessageBox::Cancel); + return; + } + puzzleImage = newImage; + setupPuzzle(); + } +} + +void MainWindow::setCompleted() +{ + QMessageBox::information(this, tr("Puzzle Completed"), + tr("Congratulations! You have completed the puzzle!\n" + "Click OK to start again."), + QMessageBox::Ok); + + setupPuzzle(); +} + +void MainWindow::setupPuzzle() +{ + int size = qMin(puzzleImage.width(), puzzleImage.height()); + puzzleImage = puzzleImage.copy((puzzleImage.width() - size)/2, + (puzzleImage.height() - size)/2, size, size).scaled(puzzleWidget->imageSize(), + puzzleWidget->imageSize(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + + qsrand(QCursor::pos().x() ^ QCursor::pos().y()); + + model->addPieces(puzzleImage); + puzzleWidget->clear(); +} + +void MainWindow::setupMenus() +{ + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + + QAction *openAction = fileMenu->addAction(tr("&Open...")); + openAction->setShortcuts(QKeySequence::Open); + + QAction *exitAction = fileMenu->addAction(tr("E&xit")); + exitAction->setShortcuts(QKeySequence::Quit); + + QMenu *gameMenu = menuBar()->addMenu(tr("&Game")); + + QAction *restartAction = gameMenu->addAction(tr("&Restart")); + + connect(openAction, SIGNAL(triggered()), this, SLOT(openImage())); + connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + connect(restartAction, SIGNAL(triggered()), this, SLOT(setupPuzzle())); +} + +void MainWindow::setupWidgets() +{ + QFrame *frame = new QFrame; + QHBoxLayout *frameLayout = new QHBoxLayout(frame); + + puzzleWidget = new PuzzleWidget(400); + + piecesList = new QListView; + piecesList->setDragEnabled(true); + piecesList->setViewMode(QListView::IconMode); + piecesList->setIconSize(QSize(puzzleWidget->pieceSize() - 20, puzzleWidget->pieceSize() - 20)); + piecesList->setGridSize(QSize(puzzleWidget->pieceSize(), puzzleWidget->pieceSize())); + piecesList->setSpacing(10); + piecesList->setMovement(QListView::Snap); + piecesList->setAcceptDrops(true); + piecesList->setDropIndicatorShown(true); + + PiecesModel *model = new PiecesModel(puzzleWidget->pieceSize(), this); + piecesList->setModel(model); + + connect(puzzleWidget, SIGNAL(puzzleCompleted()), + this, SLOT(setCompleted()), Qt::QueuedConnection); + + frameLayout->addWidget(piecesList); + frameLayout->addWidget(puzzleWidget); + setCentralWidget(frame); +} diff --git a/examples/widgets/itemviews/puzzle/mainwindow.h b/examples/widgets/itemviews/puzzle/mainwindow.h new file mode 100644 index 0000000000..83704d9932 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/mainwindow.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include + +class PuzzleWidget; +class PiecesModel; +QT_BEGIN_NAMESPACE +class QListView; +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = 0); + +public slots: + void openImage(const QString &path = QString()); + void setupPuzzle(); + +private slots: + void setCompleted(); + +private: + void setupMenus(); + void setupWidgets(); + + QPixmap puzzleImage; + QListView *piecesList; + PuzzleWidget *puzzleWidget; + PiecesModel *model; +}; + +#endif diff --git a/examples/widgets/itemviews/puzzle/piecesmodel.cpp b/examples/widgets/itemviews/puzzle/piecesmodel.cpp new file mode 100644 index 0000000000..68574606e2 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/piecesmodel.cpp @@ -0,0 +1,203 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "piecesmodel.h" + +PiecesModel::PiecesModel(int pieceSize, QObject *parent) + : QAbstractListModel(parent), m_PieceSize(pieceSize) +{ +} + +QVariant PiecesModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (role == Qt::DecorationRole) + return QIcon(pixmaps.value(index.row()).scaled(m_PieceSize, m_PieceSize, + Qt::KeepAspectRatio, Qt::SmoothTransformation)); + else if (role == Qt::UserRole) + return pixmaps.value(index.row()); + else if (role == Qt::UserRole + 1) + return locations.value(index.row()); + + return QVariant(); +} + +void PiecesModel::addPiece(const QPixmap &pixmap, const QPoint &location) +{ + int row; + if (int(2.0*qrand()/(RAND_MAX+1.0)) == 1) + row = 0; + else + row = pixmaps.size(); + + beginInsertRows(QModelIndex(), row, row); + pixmaps.insert(row, pixmap); + locations.insert(row, location); + endInsertRows(); +} + +Qt::ItemFlags PiecesModel::flags(const QModelIndex &index) const +{ + if (index.isValid()) + return (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled); + + return Qt::ItemIsDropEnabled; +} + +bool PiecesModel::removeRows(int row, int count, const QModelIndex &parent) +{ + if (parent.isValid()) + return false; + + if (row >= pixmaps.size() || row + count <= 0) + return false; + + int beginRow = qMax(0, row); + int endRow = qMin(row + count - 1, pixmaps.size() - 1); + + beginRemoveRows(parent, beginRow, endRow); + + while (beginRow <= endRow) { + pixmaps.removeAt(beginRow); + locations.removeAt(beginRow); + ++beginRow; + } + + endRemoveRows(); + return true; +} + +QStringList PiecesModel::mimeTypes() const +{ + QStringList types; + types << "image/x-puzzle-piece"; + return types; +} + +QMimeData *PiecesModel::mimeData(const QModelIndexList &indexes) const +{ + QMimeData *mimeData = new QMimeData(); + QByteArray encodedData; + + QDataStream stream(&encodedData, QIODevice::WriteOnly); + + foreach (QModelIndex index, indexes) { + if (index.isValid()) { + QPixmap pixmap = qvariant_cast(data(index, Qt::UserRole)); + QPoint location = data(index, Qt::UserRole+1).toPoint(); + stream << pixmap << location; + } + } + + mimeData->setData("image/x-puzzle-piece", encodedData); + return mimeData; +} + +bool PiecesModel::dropMimeData(const QMimeData *data, Qt::DropAction action, + int row, int column, const QModelIndex &parent) +{ + if (!data->hasFormat("image/x-puzzle-piece")) + return false; + + if (action == Qt::IgnoreAction) + return true; + + if (column > 0) + return false; + + int endRow; + + if (!parent.isValid()) { + if (row < 0) + endRow = pixmaps.size(); + else + endRow = qMin(row, pixmaps.size()); + } else + endRow = parent.row(); + + QByteArray encodedData = data->data("image/x-puzzle-piece"); + QDataStream stream(&encodedData, QIODevice::ReadOnly); + + while (!stream.atEnd()) { + QPixmap pixmap; + QPoint location; + stream >> pixmap >> location; + + beginInsertRows(QModelIndex(), endRow, endRow); + pixmaps.insert(endRow, pixmap); + locations.insert(endRow, location); + endInsertRows(); + + ++endRow; + } + + return true; +} + +int PiecesModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid()) + return 0; + else + return pixmaps.size(); +} + +Qt::DropActions PiecesModel::supportedDropActions() const +{ + return Qt::CopyAction | Qt::MoveAction; +} + +void PiecesModel::addPieces(const QPixmap& pixmap) +{ + beginRemoveRows(QModelIndex(), 0, 24); + pixmaps.clear(); + locations.clear(); + endRemoveRows(); + for (int y = 0; y < 5; ++y) { + for (int x = 0; x < 5; ++x) { + QPixmap pieceImage = pixmap.copy(x*m_PieceSize, y*m_PieceSize, m_PieceSize, m_PieceSize); + addPiece(pieceImage, QPoint(x, y)); + } + } +} diff --git a/examples/widgets/itemviews/puzzle/piecesmodel.h b/examples/widgets/itemviews/puzzle/piecesmodel.h new file mode 100644 index 0000000000..e8fa45a9a0 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/piecesmodel.h @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PIECESLIST_H +#define PIECESLIST_H + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE +class QMimeData; +QT_END_NAMESPACE + +class PiecesModel : public QAbstractListModel +{ + Q_OBJECT + +public: + PiecesModel(int pieceSize, QObject *parent = 0); + + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + bool removeRows(int row, int count, const QModelIndex &parent); + + bool dropMimeData(const QMimeData *data, Qt::DropAction action, + int row, int column, const QModelIndex &parent); + QMimeData *mimeData(const QModelIndexList &indexes) const; + QStringList mimeTypes() const; + int rowCount(const QModelIndex &parent) const; + Qt::DropActions supportedDropActions() const; + + void addPiece(const QPixmap &pixmap, const QPoint &location); + void addPieces(const QPixmap& pixmap); + +private: + QList locations; + QList pixmaps; + + int m_PieceSize; +}; + +#endif diff --git a/examples/widgets/itemviews/puzzle/puzzle.desktop b/examples/widgets/itemviews/puzzle/puzzle.desktop new file mode 100644 index 0000000000..d493e7dd41 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/puzzle.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Item Views Puzzle +Exec=/opt/usr/bin/puzzle +Icon=puzzle +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/puzzle/puzzle.pro b/examples/widgets/itemviews/puzzle/puzzle.pro new file mode 100644 index 0000000000..3f76bd8fd5 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/puzzle.pro @@ -0,0 +1,22 @@ +HEADERS = mainwindow.h \ + piecesmodel.h \ + puzzlewidget.h +RESOURCES = puzzle.qrc +SOURCES = main.cpp \ + mainwindow.cpp \ + piecesmodel.cpp \ + puzzlewidget.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/puzzle +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.jpg +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/puzzle +INSTALLS += target sources + + +wince* { + DEPLOYMENT_PLUGIN += qjpeg qgif +} + +QT += widgets + diff --git a/examples/widgets/itemviews/puzzle/puzzle.qrc b/examples/widgets/itemviews/puzzle/puzzle.qrc new file mode 100644 index 0000000000..4076cec026 --- /dev/null +++ b/examples/widgets/itemviews/puzzle/puzzle.qrc @@ -0,0 +1,5 @@ + + + example.jpg + + diff --git a/examples/widgets/itemviews/puzzle/puzzlewidget.cpp b/examples/widgets/itemviews/puzzle/puzzlewidget.cpp new file mode 100644 index 0000000000..96d8c6068f --- /dev/null +++ b/examples/widgets/itemviews/puzzle/puzzlewidget.cpp @@ -0,0 +1,214 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "puzzlewidget.h" + +PuzzleWidget::PuzzleWidget(int imageSize, QWidget *parent) + : QWidget(parent), m_ImageSize(imageSize) +{ + setAcceptDrops(true); + setMinimumSize(m_ImageSize, m_ImageSize); + setMaximumSize(m_ImageSize, m_ImageSize); +} + +void PuzzleWidget::clear() +{ + pieceLocations.clear(); + piecePixmaps.clear(); + pieceRects.clear(); + highlightedRect = QRect(); + inPlace = 0; + update(); +} + +void PuzzleWidget::dragEnterEvent(QDragEnterEvent *event) +{ + if (event->mimeData()->hasFormat("image/x-puzzle-piece")) + event->accept(); + else + event->ignore(); +} + +void PuzzleWidget::dragLeaveEvent(QDragLeaveEvent *event) +{ + QRect updateRect = highlightedRect; + highlightedRect = QRect(); + update(updateRect); + event->accept(); +} + +void PuzzleWidget::dragMoveEvent(QDragMoveEvent *event) +{ + QRect updateRect = highlightedRect.united(targetSquare(event->pos())); + + if (event->mimeData()->hasFormat("image/x-puzzle-piece") + && findPiece(targetSquare(event->pos())) == -1) { + + highlightedRect = targetSquare(event->pos()); + event->setDropAction(Qt::MoveAction); + event->accept(); + } else { + highlightedRect = QRect(); + event->ignore(); + } + + update(updateRect); +} + +void PuzzleWidget::dropEvent(QDropEvent *event) +{ + if (event->mimeData()->hasFormat("image/x-puzzle-piece") + && findPiece(targetSquare(event->pos())) == -1) { + + QByteArray pieceData = event->mimeData()->data("image/x-puzzle-piece"); + QDataStream stream(&pieceData, QIODevice::ReadOnly); + QRect square = targetSquare(event->pos()); + QPixmap pixmap; + QPoint location; + stream >> pixmap >> location; + + pieceLocations.append(location); + piecePixmaps.append(pixmap); + pieceRects.append(square); + + highlightedRect = QRect(); + update(square); + + event->setDropAction(Qt::MoveAction); + event->accept(); + + if (location == QPoint(square.x()/pieceSize(), square.y()/pieceSize())) { + inPlace++; + if (inPlace == 25) + emit puzzleCompleted(); + } + } else { + highlightedRect = QRect(); + event->ignore(); + } +} + +int PuzzleWidget::findPiece(const QRect &pieceRect) const +{ + for (int i = 0; i < pieceRects.size(); ++i) { + if (pieceRect == pieceRects[i]) { + return i; + } + } + return -1; +} + +void PuzzleWidget::mousePressEvent(QMouseEvent *event) +{ + QRect square = targetSquare(event->pos()); + int found = findPiece(square); + + if (found == -1) + return; + + QPoint location = pieceLocations[found]; + QPixmap pixmap = piecePixmaps[found]; + pieceLocations.removeAt(found); + piecePixmaps.removeAt(found); + pieceRects.removeAt(found); + + if (location == QPoint(square.x()/pieceSize(), square.y()/pieceSize())) + inPlace--; + + update(square); + + QByteArray itemData; + QDataStream dataStream(&itemData, QIODevice::WriteOnly); + + dataStream << pixmap << location; + + QMimeData *mimeData = new QMimeData; + mimeData->setData("image/x-puzzle-piece", itemData); + + QDrag *drag = new QDrag(this); + drag->setMimeData(mimeData); + drag->setHotSpot(event->pos() - square.topLeft()); + drag->setPixmap(pixmap); + + if (drag->start(Qt::MoveAction) == 0) { + pieceLocations.insert(found, location); + piecePixmaps.insert(found, pixmap); + pieceRects.insert(found, square); + update(targetSquare(event->pos())); + + if (location == QPoint(square.x()/pieceSize(), square.y()/pieceSize())) + inPlace++; + } +} + +void PuzzleWidget::paintEvent(QPaintEvent *event) +{ + QPainter painter; + painter.begin(this); + painter.fillRect(event->rect(), Qt::white); + + if (highlightedRect.isValid()) { + painter.setBrush(QColor("#ffcccc")); + painter.setPen(Qt::NoPen); + painter.drawRect(highlightedRect.adjusted(0, 0, -1, -1)); + } + + for (int i = 0; i < pieceRects.size(); ++i) { + painter.drawPixmap(pieceRects[i], piecePixmaps[i]); + } + painter.end(); +} + +const QRect PuzzleWidget::targetSquare(const QPoint &position) const +{ + return QRect(position.x()/pieceSize() * pieceSize(), position.y()/pieceSize() * pieceSize(), pieceSize(), pieceSize()); +} + +int PuzzleWidget::pieceSize() const +{ + return m_ImageSize / 5; +} + +int PuzzleWidget::imageSize() const +{ + return m_ImageSize; +} diff --git a/examples/widgets/itemviews/puzzle/puzzlewidget.h b/examples/widgets/itemviews/puzzle/puzzlewidget.h new file mode 100644 index 0000000000..1c0fc77a5f --- /dev/null +++ b/examples/widgets/itemviews/puzzle/puzzlewidget.h @@ -0,0 +1,89 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PUZZLEWIDGET_H +#define PUZZLEWIDGET_H + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE +class QDragEnterEvent; +class QDropEvent; +class QMouseEvent; +QT_END_NAMESPACE + +class PuzzleWidget : public QWidget +{ + Q_OBJECT + +public: + PuzzleWidget(int imageSize, QWidget *parent = 0); + void clear(); + + int pieceSize() const; + int imageSize() const; + +signals: + void puzzleCompleted(); + +protected: + void dragEnterEvent(QDragEnterEvent *event); + void dragLeaveEvent(QDragLeaveEvent *event); + void dragMoveEvent(QDragMoveEvent *event); + void dropEvent(QDropEvent *event); + void mousePressEvent(QMouseEvent *event); + void paintEvent(QPaintEvent *event); + +private: + int findPiece(const QRect &pieceRect) const; + const QRect targetSquare(const QPoint &position) const; + + QList piecePixmaps; + QList pieceRects; + QList pieceLocations; + QRect highlightedRect; + int inPlace; + int m_ImageSize; +}; + +#endif diff --git a/examples/widgets/itemviews/simpledommodel/domitem.cpp b/examples/widgets/itemviews/simpledommodel/domitem.cpp new file mode 100644 index 0000000000..2d7ce5a31e --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/domitem.cpp @@ -0,0 +1,101 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "domitem.h" + +//! [0] +DomItem::DomItem(QDomNode &node, int row, DomItem *parent) +{ + domNode = node; +//! [0] + // Record the item's location within its parent. +//! [1] + rowNumber = row; + parentItem = parent; +} +//! [1] + +//! [2] +DomItem::~DomItem() +{ + QHash::iterator it; + for (it = childItems.begin(); it != childItems.end(); ++it) + delete it.value(); +} +//! [2] + +//! [3] +QDomNode DomItem::node() const +{ + return domNode; +} +//! [3] + +//! [4] +DomItem *DomItem::parent() +{ + return parentItem; +} +//! [4] + +//! [5] +DomItem *DomItem::child(int i) +{ + if (childItems.contains(i)) + return childItems[i]; + + if (i >= 0 && i < domNode.childNodes().count()) { + QDomNode childNode = domNode.childNodes().item(i); + DomItem *childItem = new DomItem(childNode, i, this); + childItems[i] = childItem; + return childItem; + } + return 0; +} +//! [5] + +//! [6] +int DomItem::row() +{ + return rowNumber; +} +//! [6] diff --git a/examples/widgets/itemviews/simpledommodel/domitem.h b/examples/widgets/itemviews/simpledommodel/domitem.h new file mode 100644 index 0000000000..8e9da9dd27 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/domitem.h @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DOMITEM_H +#define DOMITEM_H + +#include +#include + +//! [0] +class DomItem +{ +public: + DomItem(QDomNode &node, int row, DomItem *parent = 0); + ~DomItem(); + DomItem *child(int i); + DomItem *parent(); + QDomNode node() const; + int row(); + +private: + QDomNode domNode; + QHash childItems; + DomItem *parentItem; + int rowNumber; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/simpledommodel/dommodel.cpp b/examples/widgets/itemviews/simpledommodel/dommodel.cpp new file mode 100644 index 0000000000..75d4c3e723 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/dommodel.cpp @@ -0,0 +1,189 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#include "domitem.h" +#include "dommodel.h" + +//! [0] +DomModel::DomModel(QDomDocument document, QObject *parent) + : QAbstractItemModel(parent), domDocument(document) +{ + rootItem = new DomItem(domDocument, 0); +} +//! [0] + +//! [1] +DomModel::~DomModel() +{ + delete rootItem; +} +//! [1] + +//! [2] +int DomModel::columnCount(const QModelIndex &/*parent*/) const +{ + return 3; +} +//! [2] + +//! [3] +QVariant DomModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (role != Qt::DisplayRole) + return QVariant(); + + DomItem *item = static_cast(index.internalPointer()); + + QDomNode node = item->node(); +//! [3] //! [4] + QStringList attributes; + QDomNamedNodeMap attributeMap = node.attributes(); + + switch (index.column()) { + case 0: + return node.nodeName(); + case 1: + for (int i = 0; i < attributeMap.count(); ++i) { + QDomNode attribute = attributeMap.item(i); + attributes << attribute.nodeName() + "=\"" + +attribute.nodeValue() + "\""; + } + return attributes.join(" "); + case 2: + return node.nodeValue().split("\n").join(" "); + default: + return QVariant(); + } +} +//! [4] + +//! [5] +Qt::ItemFlags DomModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return 0; + + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; +} +//! [5] + +//! [6] +QVariant DomModel::headerData(int section, Qt::Orientation orientation, + int role) const +{ + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { + switch (section) { + case 0: + return tr("Name"); + case 1: + return tr("Attributes"); + case 2: + return tr("Value"); + default: + return QVariant(); + } + } + + return QVariant(); +} +//! [6] + +//! [7] +QModelIndex DomModel::index(int row, int column, const QModelIndex &parent) + const +{ + if (!hasIndex(row, column, parent)) + return QModelIndex(); + + DomItem *parentItem; + + if (!parent.isValid()) + parentItem = rootItem; + else + parentItem = static_cast(parent.internalPointer()); +//! [7] + +//! [8] + DomItem *childItem = parentItem->child(row); + if (childItem) + return createIndex(row, column, childItem); + else + return QModelIndex(); +} +//! [8] + +//! [9] +QModelIndex DomModel::parent(const QModelIndex &child) const +{ + if (!child.isValid()) + return QModelIndex(); + + DomItem *childItem = static_cast(child.internalPointer()); + DomItem *parentItem = childItem->parent(); + + if (!parentItem || parentItem == rootItem) + return QModelIndex(); + + return createIndex(parentItem->row(), 0, parentItem); +} +//! [9] + +//! [10] +int DomModel::rowCount(const QModelIndex &parent) const +{ + if (parent.column() > 0) + return 0; + + DomItem *parentItem; + + if (!parent.isValid()) + parentItem = rootItem; + else + parentItem = static_cast(parent.internalPointer()); + + return parentItem->node().childNodes().count(); +} +//! [10] diff --git a/examples/widgets/itemviews/simpledommodel/dommodel.h b/examples/widgets/itemviews/simpledommodel/dommodel.h new file mode 100644 index 0000000000..386f976f79 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/dommodel.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DOMMODEL_H +#define DOMMODEL_H + +#include +#include +#include +#include + +class DomItem; + +//! [0] +class DomModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + DomModel(QDomDocument document, QObject *parent = 0); + ~DomModel(); + + QVariant data(const QModelIndex &index, int role) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &child) const; + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; + +private: + QDomDocument domDocument; + DomItem *rootItem; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/simpledommodel/main.cpp b/examples/widgets/itemviews/simpledommodel/main.cpp new file mode 100644 index 0000000000..e65d428bc6 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/main.cpp @@ -0,0 +1,52 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + MainWindow window; + window.resize(640, 480); + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/simpledommodel/mainwindow.cpp b/examples/widgets/itemviews/simpledommodel/mainwindow.cpp new file mode 100644 index 0000000000..f84d8841e7 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/mainwindow.cpp @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include "dommodel.h" +#include "mainwindow.h" + +MainWindow::MainWindow() : QMainWindow(), model(0) +{ + fileMenu = menuBar()->addMenu(tr("&File")); + fileMenu->addAction(tr("&Open..."), this, SLOT(openFile()), + QKeySequence::Open); + fileMenu->addAction(tr("E&xit"), this, SLOT(close()), + QKeySequence::Quit); + + model = new DomModel(QDomDocument(), this); + view = new QTreeView(this); + view->setModel(model); + + setCentralWidget(view); + setWindowTitle(tr("Simple DOM Model")); +} + +void MainWindow::openFile() +{ + QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"), + xmlPath, tr("XML files (*.xml);;HTML files (*.html);;" + "SVG files (*.svg);;User Interface files (*.ui)")); + + if (!filePath.isEmpty()) { + QFile file(filePath); + if (file.open(QIODevice::ReadOnly)) { + QDomDocument document; + if (document.setContent(&file)) { + DomModel *newModel = new DomModel(document, this); + view->setModel(newModel); + delete model; + model = newModel; + xmlPath = filePath; + } + file.close(); + } + } +} diff --git a/examples/widgets/itemviews/simpledommodel/mainwindow.h b/examples/widgets/itemviews/simpledommodel/mainwindow.h new file mode 100644 index 0000000000..16e0b800f9 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/mainwindow.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include + +class DomModel; +QT_BEGIN_NAMESPACE +class QMenu; +class QTreeView; +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(); + +public slots: + void openFile(); + +private: + DomModel *model; + QMenu *fileMenu; + QString xmlPath; + QTreeView *view; +}; + +#endif diff --git a/examples/widgets/itemviews/simpledommodel/simpledommodel.desktop b/examples/widgets/itemviews/simpledommodel/simpledommodel.desktop new file mode 100644 index 0000000000..a53b896848 --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/simpledommodel.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Simple DOM Model +Exec=/opt/usr/bin/simpledommodel +Icon=simpledommodel +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/simpledommodel/simpledommodel.pro b/examples/widgets/itemviews/simpledommodel/simpledommodel.pro new file mode 100644 index 0000000000..2d30e71c1a --- /dev/null +++ b/examples/widgets/itemviews/simpledommodel/simpledommodel.pro @@ -0,0 +1,16 @@ +HEADERS = domitem.h \ + dommodel.h \ + mainwindow.h +SOURCES = domitem.cpp \ + dommodel.cpp \ + main.cpp \ + mainwindow.cpp +CONFIG += qt +QT += xml widgets + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/simpledommodel +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/simpledommodel +INSTALLS += target sources + diff --git a/examples/widgets/itemviews/simpletreemodel/default.txt b/examples/widgets/itemviews/simpletreemodel/default.txt new file mode 100644 index 0000000000..2b2fb579ae --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/default.txt @@ -0,0 +1,40 @@ +Getting Started How to familiarize yourself with Qt Designer + Launching Designer Running the Qt Designer application + The User Interface How to interact with Qt Designer + +Designing a Component Creating a GUI for your application + Creating a Dialog How to create a dialog + Composing the Dialog Putting widgets into the dialog example + Creating a Layout Arranging widgets on a form + Signal and Slot Connections Making widget communicate with each other + +Using a Component in Your Application Generating code from forms + The Direct Approach Using a form without any adjustments + The Single Inheritance Approach Subclassing a form's base class + The Multiple Inheritance Approach Subclassing the form itself + Automatic Connections Connecting widgets using a naming scheme + A Dialog Without Auto-Connect How to connect widgets without a naming scheme + A Dialog With Auto-Connect Using automatic connections + +Form Editing Mode How to edit a form in Qt Designer + Managing Forms Loading and saving forms + Editing a Form Basic editing techniques + The Property Editor Changing widget properties + The Object Inspector Examining the hierarchy of objects on a form + Layouts Objects that arrange widgets on a form + Applying and Breaking Layouts Managing widgets in layouts + Horizontal and Vertical Layouts Standard row and column layouts + The Grid Layout Arranging widgets in a matrix + Previewing Forms Checking that the design works + +Using Containers How to group widgets together + General Features Common container features + Frames QFrame + Group Boxes QGroupBox + Stacked Widgets QStackedWidget + Tab Widgets QTabWidget + Toolbox Widgets QToolBox + +Connection Editing Mode Connecting widgets together with signals and slots + Connecting Objects Making connections in Qt Designer + Editing Connections Changing existing connections diff --git a/examples/widgets/itemviews/simpletreemodel/main.cpp b/examples/widgets/itemviews/simpletreemodel/main.cpp new file mode 100644 index 0000000000..a7dd720a2f --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/main.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "treemodel.h" + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(simpletreemodel); + + QApplication app(argc, argv); + + QFile file(":/default.txt"); + file.open(QIODevice::ReadOnly); + TreeModel model(file.readAll()); + file.close(); + + QTreeView view; + view.setModel(&model); + view.setWindowTitle(QObject::tr("Simple Tree Model")); + view.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/simpletreemodel/simpletreemodel.desktop b/examples/widgets/itemviews/simpletreemodel/simpletreemodel.desktop new file mode 100644 index 0000000000..361202f5c0 --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/simpletreemodel.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Simple Tree Model +Exec=/opt/usr/bin/simpletreemodel +Icon=simpletreemodel +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/simpletreemodel/simpletreemodel.pro b/examples/widgets/itemviews/simpletreemodel/simpletreemodel.pro new file mode 100644 index 0000000000..cd4f8af604 --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/simpletreemodel.pro @@ -0,0 +1,15 @@ +HEADERS = treeitem.h \ + treemodel.h +RESOURCES = simpletreemodel.qrc +SOURCES = treeitem.cpp \ + treemodel.cpp \ + main.cpp +CONFIG += qt + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/simpletreemodel +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.txt +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/simpletreemodel +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/simpletreemodel/simpletreemodel.qrc b/examples/widgets/itemviews/simpletreemodel/simpletreemodel.qrc new file mode 100644 index 0000000000..a8ecc98d28 --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/simpletreemodel.qrc @@ -0,0 +1,5 @@ + + + default.txt + + diff --git a/examples/widgets/itemviews/simpletreemodel/treeitem.cpp b/examples/widgets/itemviews/simpletreemodel/treeitem.cpp new file mode 100644 index 0000000000..a296f6ccd5 --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/treeitem.cpp @@ -0,0 +1,116 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + treeitem.cpp + + A container for items of data supplied by the simple tree model. +*/ + +#include + +#include "treeitem.h" + +//! [0] +TreeItem::TreeItem(const QList &data, TreeItem *parent) +{ + parentItem = parent; + itemData = data; +} +//! [0] + +//! [1] +TreeItem::~TreeItem() +{ + qDeleteAll(childItems); +} +//! [1] + +//! [2] +void TreeItem::appendChild(TreeItem *item) +{ + childItems.append(item); +} +//! [2] + +//! [3] +TreeItem *TreeItem::child(int row) +{ + return childItems.value(row); +} +//! [3] + +//! [4] +int TreeItem::childCount() const +{ + return childItems.count(); +} +//! [4] + +//! [5] +int TreeItem::columnCount() const +{ + return itemData.count(); +} +//! [5] + +//! [6] +QVariant TreeItem::data(int column) const +{ + return itemData.value(column); +} +//! [6] + +//! [7] +TreeItem *TreeItem::parent() +{ + return parentItem; +} +//! [7] + +//! [8] +int TreeItem::row() const +{ + if (parentItem) + return parentItem->childItems.indexOf(const_cast(this)); + + return 0; +} +//! [8] diff --git a/examples/widgets/itemviews/simpletreemodel/treeitem.h b/examples/widgets/itemviews/simpletreemodel/treeitem.h new file mode 100644 index 0000000000..b2a7a83066 --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/treeitem.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TREEITEM_H +#define TREEITEM_H + +#include +#include + +//! [0] +class TreeItem +{ +public: + TreeItem(const QList &data, TreeItem *parent = 0); + ~TreeItem(); + + void appendChild(TreeItem *child); + + TreeItem *child(int row); + int childCount() const; + int columnCount() const; + QVariant data(int column) const; + int row() const; + TreeItem *parent(); + +private: + QList childItems; + QList itemData; + TreeItem *parentItem; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/simpletreemodel/treemodel.cpp b/examples/widgets/itemviews/simpletreemodel/treemodel.cpp new file mode 100644 index 0000000000..1fad9ba347 --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/treemodel.cpp @@ -0,0 +1,218 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + treemodel.cpp + + Provides a simple tree model to show how to create and use hierarchical + models. +*/ + +#include + +#include "treeitem.h" +#include "treemodel.h" + +//! [0] +TreeModel::TreeModel(const QString &data, QObject *parent) + : QAbstractItemModel(parent) +{ + QList rootData; + rootData << "Title" << "Summary"; + rootItem = new TreeItem(rootData); + setupModelData(data.split(QString("\n")), rootItem); +} +//! [0] + +//! [1] +TreeModel::~TreeModel() +{ + delete rootItem; +} +//! [1] + +//! [2] +int TreeModel::columnCount(const QModelIndex &parent) const +{ + if (parent.isValid()) + return static_cast(parent.internalPointer())->columnCount(); + else + return rootItem->columnCount(); +} +//! [2] + +//! [3] +QVariant TreeModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if (role != Qt::DisplayRole) + return QVariant(); + + TreeItem *item = static_cast(index.internalPointer()); + + return item->data(index.column()); +} +//! [3] + +//! [4] +Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) + return 0; + + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; +} +//! [4] + +//! [5] +QVariant TreeModel::headerData(int section, Qt::Orientation orientation, + int role) const +{ + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) + return rootItem->data(section); + + return QVariant(); +} +//! [5] + +//! [6] +QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) + const +{ + if (!hasIndex(row, column, parent)) + return QModelIndex(); + + TreeItem *parentItem; + + if (!parent.isValid()) + parentItem = rootItem; + else + parentItem = static_cast(parent.internalPointer()); + + TreeItem *childItem = parentItem->child(row); + if (childItem) + return createIndex(row, column, childItem); + else + return QModelIndex(); +} +//! [6] + +//! [7] +QModelIndex TreeModel::parent(const QModelIndex &index) const +{ + if (!index.isValid()) + return QModelIndex(); + + TreeItem *childItem = static_cast(index.internalPointer()); + TreeItem *parentItem = childItem->parent(); + + if (parentItem == rootItem) + return QModelIndex(); + + return createIndex(parentItem->row(), 0, parentItem); +} +//! [7] + +//! [8] +int TreeModel::rowCount(const QModelIndex &parent) const +{ + TreeItem *parentItem; + if (parent.column() > 0) + return 0; + + if (!parent.isValid()) + parentItem = rootItem; + else + parentItem = static_cast(parent.internalPointer()); + + return parentItem->childCount(); +} +//! [8] + +void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) +{ + QList parents; + QList indentations; + parents << parent; + indentations << 0; + + int number = 0; + + while (number < lines.count()) { + int position = 0; + while (position < lines[number].length()) { + if (lines[number].mid(position, 1) != " ") + break; + position++; + } + + QString lineData = lines[number].mid(position).trimmed(); + + if (!lineData.isEmpty()) { + // Read the column data from the rest of the line. + QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); + QList columnData; + for (int column = 0; column < columnStrings.count(); ++column) + columnData << columnStrings[column]; + + if (position > indentations.last()) { + // The last child of the current parent is now the new parent + // unless the current parent has no children. + + if (parents.last()->childCount() > 0) { + parents << parents.last()->child(parents.last()->childCount()-1); + indentations << position; + } + } else { + while (position < indentations.last() && parents.count() > 0) { + parents.pop_back(); + indentations.pop_back(); + } + } + + // Append a new item to the current parent's list of children. + parents.last()->appendChild(new TreeItem(columnData, parents.last())); + } + + number++; + } +} diff --git a/examples/widgets/itemviews/simpletreemodel/treemodel.h b/examples/widgets/itemviews/simpletreemodel/treemodel.h new file mode 100644 index 0000000000..9cf870c0fc --- /dev/null +++ b/examples/widgets/itemviews/simpletreemodel/treemodel.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TREEMODEL_H +#define TREEMODEL_H + +#include +#include +#include + +class TreeItem; + +//! [0] +class TreeModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + TreeModel(const QString &data, QObject *parent = 0); + ~TreeModel(); + + QVariant data(const QModelIndex &index, int role) const; + Qt::ItemFlags flags(const QModelIndex &index) const; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex &index) const; + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; + +private: + void setupModelData(const QStringList &lines, TreeItem *parent); + + TreeItem *rootItem; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/simplewidgetmapper/main.cpp b/examples/widgets/itemviews/simplewidgetmapper/main.cpp new file mode 100644 index 0000000000..0fc4966ccf --- /dev/null +++ b/examples/widgets/itemviews/simplewidgetmapper/main.cpp @@ -0,0 +1,51 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + Window window; + window.show(); + return app.exec(); +} diff --git a/examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.desktop b/examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.desktop new file mode 100644 index 0000000000..6b09a236da --- /dev/null +++ b/examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Simple Widget Mapper +Exec=/opt/usr/bin/simplewidgetmapper +Icon=simplewidgetmapper +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.pro b/examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.pro new file mode 100644 index 0000000000..3b2fd8b257 --- /dev/null +++ b/examples/widgets/itemviews/simplewidgetmapper/simplewidgetmapper.pro @@ -0,0 +1,11 @@ +HEADERS = window.h +SOURCES = main.cpp \ + window.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/simplewidgetmapper +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/simplewidgetmapper +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/itemviews/simplewidgetmapper/window.cpp b/examples/widgets/itemviews/simplewidgetmapper/window.cpp new file mode 100644 index 0000000000..5b5ed8f231 --- /dev/null +++ b/examples/widgets/itemviews/simplewidgetmapper/window.cpp @@ -0,0 +1,133 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "window.h" + +//! [Set up widgets] +Window::Window(QWidget *parent) + : QWidget(parent) +{ + setupModel(); + + nameLabel = new QLabel(tr("Na&me:")); + nameEdit = new QLineEdit(); + addressLabel = new QLabel(tr("&Address:")); + addressEdit = new QTextEdit(); + ageLabel = new QLabel(tr("A&ge (in years):")); + ageSpinBox = new QSpinBox(); + nextButton = new QPushButton(tr("&Next")); + previousButton = new QPushButton(tr("&Previous")); + + nameLabel->setBuddy(nameEdit); + addressLabel->setBuddy(addressEdit); + ageLabel->setBuddy(ageSpinBox); +//! [Set up widgets] + +//! [Set up the mapper] + mapper = new QDataWidgetMapper(this); + mapper->setModel(model); + mapper->addMapping(nameEdit, 0); + mapper->addMapping(addressEdit, 1); + mapper->addMapping(ageSpinBox, 2); + + connect(previousButton, SIGNAL(clicked()), + mapper, SLOT(toPrevious())); + connect(nextButton, SIGNAL(clicked()), + mapper, SLOT(toNext())); + connect(mapper, SIGNAL(currentIndexChanged(int)), + this, SLOT(updateButtons(int))); +//! [Set up the mapper] + +//! [Set up the layout] + QGridLayout *layout = new QGridLayout(); + layout->addWidget(nameLabel, 0, 0, 1, 1); + layout->addWidget(nameEdit, 0, 1, 1, 1); + layout->addWidget(previousButton, 0, 2, 1, 1); + layout->addWidget(addressLabel, 1, 0, 1, 1); + layout->addWidget(addressEdit, 1, 1, 2, 1); + layout->addWidget(nextButton, 1, 2, 1, 1); + layout->addWidget(ageLabel, 3, 0, 1, 1); + layout->addWidget(ageSpinBox, 3, 1, 1, 1); + setLayout(layout); + + setWindowTitle(tr("Simple Widget Mapper")); + mapper->toFirst(); +} +//! [Set up the layout] + +//! [Set up the model] +void Window::setupModel() +{ + model = new QStandardItemModel(5, 3, this); + + QStringList names; + names << "Alice" << "Bob" << "Carol" << "Donald" << "Emma"; + + QStringList addresses; + addresses << "123 Main Street
Market Town
" + << "PO Box 32
Mail Handling Service" + "
Service City
" + << "The Lighthouse
Remote Island
" + << "47338 Park Avenue
Big City
" + << "Research Station
Base Camp
Big Mountain
"; + + QStringList ages; + ages << "20" << "31" << "32" << "19" << "26"; + + for (int row = 0; row < 5; ++row) { + QStandardItem *item = new QStandardItem(names[row]); + model->setItem(row, 0, item); + item = new QStandardItem(addresses[row]); + model->setItem(row, 1, item); + item = new QStandardItem(ages[row]); + model->setItem(row, 2, item); + } +} +//! [Set up the model] + +//! [Slot for updating the buttons] +void Window::updateButtons(int row) +{ + previousButton->setEnabled(row > 0); + nextButton->setEnabled(row < model->rowCount() - 1); +} +//! [Slot for updating the buttons] diff --git a/examples/widgets/itemviews/simplewidgetmapper/window.h b/examples/widgets/itemviews/simplewidgetmapper/window.h new file mode 100644 index 0000000000..77772e522f --- /dev/null +++ b/examples/widgets/itemviews/simplewidgetmapper/window.h @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include + +QT_BEGIN_NAMESPACE +class QDataWidgetMapper; +class QLabel; +class QLineEdit; +class QPushButton; +class QSpinBox; +class QStandardItemModel; +class QTextEdit; +QT_END_NAMESPACE + +//! [Window definition] +class Window : public QWidget +{ + Q_OBJECT + +public: + Window(QWidget *parent = 0); + +private slots: + void updateButtons(int row); + +private: + void setupModel(); + + QLabel *nameLabel; + QLabel *addressLabel; + QLabel *ageLabel; + QLineEdit *nameEdit; + QTextEdit *addressEdit; + QSpinBox *ageSpinBox; + QPushButton *nextButton; + QPushButton *previousButton; + + QStandardItemModel *model; + QDataWidgetMapper *mapper; +}; +//! [Window definition] + +#endif diff --git a/examples/widgets/itemviews/spinboxdelegate/delegate.cpp b/examples/widgets/itemviews/spinboxdelegate/delegate.cpp new file mode 100644 index 0000000000..2967b6ae38 --- /dev/null +++ b/examples/widgets/itemviews/spinboxdelegate/delegate.cpp @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + delegate.cpp + + A delegate that allows the user to change integer values from the model + using a spin box widget. +*/ + +#include + +#include "delegate.h" + + +//! [0] +SpinBoxDelegate::SpinBoxDelegate(QObject *parent) + : QItemDelegate(parent) +{ +} +//! [0] + +//! [1] +QWidget *SpinBoxDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem &/* option */, + const QModelIndex &/* index */) const +{ + QSpinBox *editor = new QSpinBox(parent); + editor->setMinimum(0); + editor->setMaximum(100); + + return editor; +} +//! [1] + +//! [2] +void SpinBoxDelegate::setEditorData(QWidget *editor, + const QModelIndex &index) const +{ + int value = index.model()->data(index, Qt::EditRole).toInt(); + + QSpinBox *spinBox = static_cast(editor); + spinBox->setValue(value); +} +//! [2] + +//! [3] +void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const +{ + QSpinBox *spinBox = static_cast(editor); + spinBox->interpretText(); + int value = spinBox->value(); + + model->setData(index, value, Qt::EditRole); +} +//! [3] + +//! [4] +void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, + const QStyleOptionViewItem &option, const QModelIndex &/* index */) const +{ + editor->setGeometry(option.rect); +} +//! [4] diff --git a/examples/widgets/itemviews/spinboxdelegate/delegate.h b/examples/widgets/itemviews/spinboxdelegate/delegate.h new file mode 100644 index 0000000000..19d647043d --- /dev/null +++ b/examples/widgets/itemviews/spinboxdelegate/delegate.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DELEGATE_H +#define DELEGATE_H + +#include +#include +#include +#include +#include + +//! [0] +class SpinBoxDelegate : public QItemDelegate +{ + Q_OBJECT + +public: + SpinBoxDelegate(QObject *parent = 0); + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + + void setEditorData(QWidget *editor, const QModelIndex &index) const; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const; + + void updateEditorGeometry(QWidget *editor, + const QStyleOptionViewItem &option, const QModelIndex &index) const; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/spinboxdelegate/main.cpp b/examples/widgets/itemviews/spinboxdelegate/main.cpp new file mode 100644 index 0000000000..6fdffad3ac --- /dev/null +++ b/examples/widgets/itemviews/spinboxdelegate/main.cpp @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + main.cpp + + A simple example that shows how a view can use a custom delegate to edit + data obtained from a model. +*/ + +#include +#include +#include +#include +#include + +#include "delegate.h" + +//! [0] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QStandardItemModel model(4, 2); + QTableView tableView; + tableView.setModel(&model); + + SpinBoxDelegate delegate; + tableView.setItemDelegate(&delegate); +//! [0] + + tableView.horizontalHeader()->setStretchLastSection(true); + +//! [1] + for (int row = 0; row < 4; ++row) { + for (int column = 0; column < 2; ++column) { + QModelIndex index = model.index(row, column, QModelIndex()); + model.setData(index, QVariant((row+1) * (column+1))); + } +//! [1] //! [2] + } +//! [2] + +//! [3] + tableView.setWindowTitle(QObject::tr("Spin Box Delegate")); + tableView.show(); + return app.exec(); +} +//! [3] diff --git a/examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.desktop b/examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.desktop new file mode 100644 index 0000000000..347e408e96 --- /dev/null +++ b/examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Spin Box Delegate +Exec=/opt/usr/bin/spinboxdelegate +Icon=spinboxdelegate +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.pro b/examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.pro new file mode 100644 index 0000000000..f6416ff936 --- /dev/null +++ b/examples/widgets/itemviews/spinboxdelegate/spinboxdelegate.pro @@ -0,0 +1,13 @@ +HEADERS = delegate.h +SOURCES = delegate.cpp \ + main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/spinboxdelegate +sources.files = $$SOURCES $$HEADERS *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/spinboxdelegate +INSTALLS += target sources + +QT += widgets + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/itemviews/spreadsheet/images/interview.png b/examples/widgets/itemviews/spreadsheet/images/interview.png new file mode 100644 index 0000000000..0c3d690258 Binary files /dev/null and b/examples/widgets/itemviews/spreadsheet/images/interview.png differ diff --git a/examples/widgets/itemviews/spreadsheet/main.cpp b/examples/widgets/itemviews/spreadsheet/main.cpp new file mode 100644 index 0000000000..92b890f735 --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/main.cpp @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "spreadsheet.h" + +int main(int argc, char** argv) { + Q_INIT_RESOURCE(spreadsheet); + QApplication app(argc, argv); + SpreadSheet sheet(10, 6); + sheet.setWindowIcon(QPixmap(":/images/interview.png")); + sheet.resize(640, 420); + sheet.show(); + return app.exec(); +} + + diff --git a/examples/widgets/itemviews/spreadsheet/printview.cpp b/examples/widgets/itemviews/spreadsheet/printview.cpp new file mode 100644 index 0000000000..fe94fde63c --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/printview.cpp @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "printview.h" + +#ifndef QT_NO_PRINTER +#include +#endif +#include + +PrintView::PrintView() +{ + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); +} + +void PrintView::print(QPrinter *printer) +{ +#ifndef QT_NO_PRINTER + resize(printer->width(), printer->height()); + render(printer); +#endif +} + diff --git a/examples/widgets/itemviews/spreadsheet/printview.h b/examples/widgets/itemviews/spreadsheet/printview.h new file mode 100644 index 0000000000..c7674f88ce --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/printview.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PRINTVIEW_H +#define PRINTVIEW_H + +#include +QT_BEGIN_NAMESPACE +class QPrinter; +QT_END_NAMESPACE + +class PrintView : public QTableView +{ + Q_OBJECT + +public: + PrintView(); + +public Q_SLOTS: + void print(QPrinter *printer); +}; + +#endif // PRINTVIEW_H + + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp new file mode 100644 index 0000000000..5dff7dc059 --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.cpp @@ -0,0 +1,639 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#ifndef QT_NO_PRINTER +#include +#include +#include +#endif + +#include "spreadsheet.h" +#include "spreadsheetdelegate.h" +#include "spreadsheetitem.h" +#include "printview.h" + +SpreadSheet::SpreadSheet(int rows, int cols, QWidget *parent) + : QMainWindow(parent) +{ + addToolBar(toolBar = new QToolBar()); + formulaInput = new QLineEdit(); + + cellLabel = new QLabel(toolBar); + cellLabel->setMinimumSize(80, 0); + + toolBar->addWidget(cellLabel); + toolBar->addWidget(formulaInput); + + table = new QTableWidget(rows, cols, this); + for (int c = 0; c < cols; ++c) { + QString character(QChar('A' + c)); + table->setHorizontalHeaderItem(c, new QTableWidgetItem(character)); + } + + table->setItemPrototype(table->item(rows -1, cols - 1)); + table->setItemDelegate(new SpreadSheetDelegate()); + + createActions(); + updateColor(0); + setupMenuBar(); + setupContents(); + setupContextMenu(); + setCentralWidget(table); + + statusBar(); + connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), + this, SLOT(updateStatus(QTableWidgetItem*))); + connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), + this, SLOT(updateColor(QTableWidgetItem*))); + connect(table, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), + this, SLOT(updateLineEdit(QTableWidgetItem*))); + connect(table, SIGNAL(itemChanged(QTableWidgetItem*)), + this, SLOT(updateStatus(QTableWidgetItem*))); + connect(formulaInput, SIGNAL(returnPressed()), this, SLOT(returnPressed())); + connect(table, SIGNAL(itemChanged(QTableWidgetItem*)), + this, SLOT(updateLineEdit(QTableWidgetItem*))); + + setWindowTitle(tr("Spreadsheet")); +} + +void SpreadSheet::createActions() +{ + cell_sumAction = new QAction(tr("Sum"), this); + connect(cell_sumAction, SIGNAL(triggered()), this, SLOT(actionSum())); + + cell_addAction = new QAction(tr("&Add"), this); + cell_addAction->setShortcut(Qt::CTRL | Qt::Key_Plus); + connect(cell_addAction, SIGNAL(triggered()), this, SLOT(actionAdd())); + + cell_subAction = new QAction(tr("&Subtract"), this); + cell_subAction->setShortcut(Qt::CTRL | Qt::Key_Minus); + connect(cell_subAction, SIGNAL(triggered()), this, SLOT(actionSubtract())); + + cell_mulAction = new QAction(tr("&Multiply"), this); + cell_mulAction->setShortcut(Qt::CTRL | Qt::Key_multiply); + connect(cell_mulAction, SIGNAL(triggered()), this, SLOT(actionMultiply())); + + cell_divAction = new QAction(tr("&Divide"), this); + cell_divAction->setShortcut(Qt::CTRL | Qt::Key_division); + connect(cell_divAction, SIGNAL(triggered()), this, SLOT(actionDivide())); + + fontAction = new QAction(tr("Font..."), this); + fontAction->setShortcut(Qt::CTRL | Qt::Key_F); + connect(fontAction, SIGNAL(triggered()), this, SLOT(selectFont())); + + colorAction = new QAction(QPixmap(16, 16), tr("Background &Color..."), this); + connect(colorAction, SIGNAL(triggered()), this, SLOT(selectColor())); + + clearAction = new QAction(tr("Clear"), this); + clearAction->setShortcut(Qt::Key_Delete); + connect(clearAction, SIGNAL(triggered()), this, SLOT(clear())); + + aboutSpreadSheet = new QAction(tr("About Spreadsheet"), this); + connect(aboutSpreadSheet, SIGNAL(triggered()), this, SLOT(showAbout())); + + exitAction = new QAction(tr("E&xit"), this); + connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + + printAction = new QAction(tr("&Print"), this); + connect(printAction, SIGNAL(triggered()), this, SLOT(print())); + + firstSeparator = new QAction(this); + firstSeparator->setSeparator(true); + + secondSeparator = new QAction(this); + secondSeparator->setSeparator(true); +} + +void SpreadSheet::setupMenuBar() +{ + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + fileMenu->addAction(printAction); + fileMenu->addAction(exitAction); + + QMenu *cellMenu = menuBar()->addMenu(tr("&Cell")); + cellMenu->addAction(cell_addAction); + cellMenu->addAction(cell_subAction); + cellMenu->addAction(cell_mulAction); + cellMenu->addAction(cell_divAction); + cellMenu->addAction(cell_sumAction); + cellMenu->addSeparator(); + cellMenu->addAction(colorAction); + cellMenu->addAction(fontAction); + + menuBar()->addSeparator(); + + QMenu *aboutMenu = menuBar()->addMenu(tr("&Help")); + aboutMenu->addAction(aboutSpreadSheet); +} + +void SpreadSheet::updateStatus(QTableWidgetItem *item) +{ + if (item && item == table->currentItem()) { + statusBar()->showMessage(item->data(Qt::StatusTipRole).toString(), + 1000); + cellLabel->setText(tr("Cell: (%1)").arg(encode_pos(table->row(item), + table->column(item)))); + } +} + +void SpreadSheet::updateColor(QTableWidgetItem *item) +{ + QPixmap pix(16, 16); + QColor col; + if (item) + col = item->backgroundColor(); + if (!col.isValid()) + col = palette().base().color(); + + QPainter pt(&pix); + pt.fillRect(0, 0, 16, 16, col); + + QColor lighter = col.light(); + pt.setPen(lighter); + QPoint lightFrame[] = { QPoint(0, 15), QPoint(0, 0), QPoint(15, 0) }; + pt.drawPolyline(lightFrame, 3); + + pt.setPen(col.dark()); + QPoint darkFrame[] = { QPoint(1, 15), QPoint(15, 15), QPoint(15, 1) }; + pt.drawPolyline(darkFrame, 3); + + pt.end(); + + colorAction->setIcon(pix); +} + +void SpreadSheet::updateLineEdit(QTableWidgetItem *item) +{ + if (item != table->currentItem()) + return; + if (item) + formulaInput->setText(item->data(Qt::EditRole).toString()); + else + formulaInput->clear(); +} + +void SpreadSheet::returnPressed() +{ + QString text = formulaInput->text(); + int row = table->currentRow(); + int col = table->currentColumn(); + QTableWidgetItem *item = table->item(row, col); + if (!item) + table->setItem(row, col, new SpreadSheetItem(text)); + else + item->setData(Qt::EditRole, text); + table->viewport()->update(); +} + +void SpreadSheet::selectColor() +{ + QTableWidgetItem *item = table->currentItem(); + QColor col = item ? item->backgroundColor() : table->palette().base().color(); + col = QColorDialog::getColor(col, this); + if (!col.isValid()) + return; + + QList selected = table->selectedItems(); + if (selected.count() == 0) + return; + + foreach(QTableWidgetItem *i, selected) + if (i) + i->setBackgroundColor(col); + + updateColor(table->currentItem()); +} + +void SpreadSheet::selectFont() +{ + QList selected = table->selectedItems(); + if (selected.count() == 0) + return; + + bool ok = false; + QFont fnt = QFontDialog::getFont(&ok, font(), this); + + if (!ok) + return; + foreach(QTableWidgetItem *i, selected) + if (i) + i->setFont(fnt); +} + +bool SpreadSheet::runInputDialog(const QString &title, + const QString &c1Text, + const QString &c2Text, + const QString &opText, + const QString &outText, + QString *cell1, QString *cell2, QString *outCell) +{ + QStringList rows, cols; + for (int c = 0; c < table->columnCount(); ++c) + cols << QChar('A' + c); + for (int r = 0; r < table->rowCount(); ++r) + rows << QString::number(1 + r); + + QDialog addDialog(this); + addDialog.setWindowTitle(title); + + QGroupBox group(title, &addDialog); + group.setMinimumSize(250, 100); + + QLabel cell1Label(c1Text, &group); + QComboBox cell1RowInput(&group); + int c1Row, c1Col; + decode_pos(*cell1, &c1Row, &c1Col); + cell1RowInput.addItems(rows); + cell1RowInput.setCurrentIndex(c1Row); + + QComboBox cell1ColInput(&group); + cell1ColInput.addItems(cols); + cell1ColInput.setCurrentIndex(c1Col); + + QLabel operatorLabel(opText, &group); + operatorLabel.setAlignment(Qt::AlignHCenter); + + QLabel cell2Label(c2Text, &group); + QComboBox cell2RowInput(&group); + int c2Row, c2Col; + decode_pos(*cell2, &c2Row, &c2Col); + cell2RowInput.addItems(rows); + cell2RowInput.setCurrentIndex(c2Row); + QComboBox cell2ColInput(&group); + cell2ColInput.addItems(cols); + cell2ColInput.setCurrentIndex(c2Col); + + QLabel equalsLabel("=", &group); + equalsLabel.setAlignment(Qt::AlignHCenter); + + QLabel outLabel(outText, &group); + QComboBox outRowInput(&group); + int outRow, outCol; + decode_pos(*outCell, &outRow, &outCol); + outRowInput.addItems(rows); + outRowInput.setCurrentIndex(outRow); + QComboBox outColInput(&group); + outColInput.addItems(cols); + outColInput.setCurrentIndex(outCol); + + QPushButton cancelButton(tr("Cancel"), &addDialog); + connect(&cancelButton, SIGNAL(clicked()), &addDialog, SLOT(reject())); + + QPushButton okButton(tr("OK"), &addDialog); + okButton.setDefault(true); + connect(&okButton, SIGNAL(clicked()), &addDialog, SLOT(accept())); + + QHBoxLayout *buttonsLayout = new QHBoxLayout; + buttonsLayout->addStretch(1); + buttonsLayout->addWidget(&okButton); + buttonsLayout->addSpacing(10); + buttonsLayout->addWidget(&cancelButton); + + QVBoxLayout *dialogLayout = new QVBoxLayout(&addDialog); + dialogLayout->addWidget(&group); + dialogLayout->addStretch(1); + dialogLayout->addItem(buttonsLayout); + + QHBoxLayout *cell1Layout = new QHBoxLayout; + cell1Layout->addWidget(&cell1Label); + cell1Layout->addSpacing(10); + cell1Layout->addWidget(&cell1ColInput); + cell1Layout->addSpacing(10); + cell1Layout->addWidget(&cell1RowInput); + + QHBoxLayout *cell2Layout = new QHBoxLayout; + cell2Layout->addWidget(&cell2Label); + cell2Layout->addSpacing(10); + cell2Layout->addWidget(&cell2ColInput); + cell2Layout->addSpacing(10); + cell2Layout->addWidget(&cell2RowInput); + + QHBoxLayout *outLayout = new QHBoxLayout; + outLayout->addWidget(&outLabel); + outLayout->addSpacing(10); + outLayout->addWidget(&outColInput); + outLayout->addSpacing(10); + outLayout->addWidget(&outRowInput); + + QVBoxLayout *vLayout = new QVBoxLayout(&group); + vLayout->addItem(cell1Layout); + vLayout->addWidget(&operatorLabel); + vLayout->addItem(cell2Layout); + vLayout->addWidget(&equalsLabel); + vLayout->addStretch(1); + vLayout->addItem(outLayout); + + if (addDialog.exec()) { + *cell1 = cell1ColInput.currentText() + cell1RowInput.currentText(); + *cell2 = cell2ColInput.currentText() + cell2RowInput.currentText(); + *outCell = outColInput.currentText() + outRowInput.currentText(); + return true; + } + + return false; +} + +void SpreadSheet::actionSum() +{ + int row_first = 0; + int row_last = 0; + int row_cur = 0; + + int col_first = 0; + int col_last = 0; + int col_cur = 0; + + QList selected = table->selectedItems(); + + if (!selected.isEmpty()) { + QTableWidgetItem *first = selected.first(); + QTableWidgetItem *last = selected.last(); + row_first = table->row(first); + row_last = table->row(last); + col_first = table->column(first); + col_last = table->column(last); + } + + QTableWidgetItem *current = table->currentItem(); + + if (current) { + row_cur = table->row(current); + col_cur = table->column(current); + } + + QString cell1 = encode_pos(row_first, col_first); + QString cell2 = encode_pos(row_last, col_last); + QString out = encode_pos(row_cur, col_cur); + + if (runInputDialog(tr("Sum cells"), tr("First cell:"), tr("Last cell:"), + QString("%1").arg(QChar(0x03a3)), tr("Output to:"), + &cell1, &cell2, &out)) { + int row, col; + decode_pos(out, &row, &col); + table->item(row, col)->setText(tr("sum %1 %2").arg(cell1, cell2)); + } +} + +void SpreadSheet::actionMath_helper(const QString &title, const QString &op) +{ + QString cell1 = "C1"; + QString cell2 = "C2"; + QString out = "C3"; + + QTableWidgetItem *current = table->currentItem(); + if (current) + out = encode_pos(table->currentRow(), table->currentColumn()); + + if (runInputDialog(title, tr("Cell 1"), tr("Cell 2"), op, tr("Output to:"), + &cell1, &cell2, &out)) { + int row, col; + decode_pos(out, &row, &col); + table->item(row, col)->setText(tr("%1 %2 %3").arg(op, cell1, cell2)); + } +} + +void SpreadSheet::actionAdd() +{ + actionMath_helper(tr("Addition"), "+"); +} + +void SpreadSheet::actionSubtract() +{ + actionMath_helper(tr("Subtraction"), "-"); +} + +void SpreadSheet::actionMultiply() +{ + actionMath_helper(tr("Multiplication"), "*"); +} +void SpreadSheet::actionDivide() +{ + actionMath_helper(tr("Division"), "/"); +} + +void SpreadSheet::clear() +{ + foreach (QTableWidgetItem *i, table->selectedItems()) + i->setText(""); +} + +void SpreadSheet::setupContextMenu() +{ + addAction(cell_addAction); + addAction(cell_subAction); + addAction(cell_mulAction); + addAction(cell_divAction); + addAction(cell_sumAction); + addAction(firstSeparator); + addAction(colorAction); + addAction(fontAction); + addAction(secondSeparator); + addAction(clearAction); + setContextMenuPolicy(Qt::ActionsContextMenu); +} + +void SpreadSheet::setupContents() +{ + QColor titleBackground(Qt::lightGray); + QFont titleFont = table->font(); + titleFont.setBold(true); + + // column 0 + table->setItem(0, 0, new SpreadSheetItem("Item")); + table->item(0, 0)->setBackgroundColor(titleBackground); + table->item(0, 0)->setToolTip("This column shows the purchased item/service"); + table->item(0, 0)->setFont(titleFont); + + table->setItem(1, 0, new SpreadSheetItem("AirportBus")); + table->setItem(2, 0, new SpreadSheetItem("Flight (Munich)")); + table->setItem(3, 0, new SpreadSheetItem("Lunch")); + table->setItem(4, 0, new SpreadSheetItem("Flight (LA)")); + table->setItem(5, 0, new SpreadSheetItem("Taxi")); + table->setItem(6, 0, new SpreadSheetItem("Dinner")); + table->setItem(7, 0, new SpreadSheetItem("Hotel")); + table->setItem(8, 0, new SpreadSheetItem("Flight (Oslo)")); + table->setItem(9, 0, new SpreadSheetItem("Total:")); + + table->item(9, 0)->setFont(titleFont); + table->item(9, 0)->setBackgroundColor(Qt::lightGray); + + // column 1 + table->setItem(0, 1, new SpreadSheetItem("Date")); + table->item(0, 1)->setBackgroundColor(titleBackground); + table->item(0, 1)->setToolTip("This column shows the purchase date, double click to change"); + table->item(0, 1)->setFont(titleFont); + + table->setItem(1, 1, new SpreadSheetItem("15/6/2006")); + table->setItem(2, 1, new SpreadSheetItem("15/6/2006")); + table->setItem(3, 1, new SpreadSheetItem("15/6/2006")); + table->setItem(4, 1, new SpreadSheetItem("21/5/2006")); + table->setItem(5, 1, new SpreadSheetItem("16/6/2006")); + table->setItem(6, 1, new SpreadSheetItem("16/6/2006")); + table->setItem(7, 1, new SpreadSheetItem("16/6/2006")); + table->setItem(8, 1, new SpreadSheetItem("18/6/2006")); + + table->setItem(9, 1, new SpreadSheetItem()); + table->item(9, 1)->setBackgroundColor(Qt::lightGray); + + // column 2 + table->setItem(0, 2, new SpreadSheetItem("Price")); + table->item(0, 2)->setBackgroundColor(titleBackground); + table->item(0, 2)->setToolTip("This column shows the price of the purchase"); + table->item(0, 2)->setFont(titleFont); + + table->setItem(1, 2, new SpreadSheetItem("150")); + table->setItem(2, 2, new SpreadSheetItem("2350")); + table->setItem(3, 2, new SpreadSheetItem("-14")); + table->setItem(4, 2, new SpreadSheetItem("980")); + table->setItem(5, 2, new SpreadSheetItem("5")); + table->setItem(6, 2, new SpreadSheetItem("120")); + table->setItem(7, 2, new SpreadSheetItem("300")); + table->setItem(8, 2, new SpreadSheetItem("1240")); + + table->setItem(9, 2, new SpreadSheetItem()); + table->item(9, 2)->setBackgroundColor(Qt::lightGray); + + // column 3 + table->setItem(0, 3, new SpreadSheetItem("Currency")); + table->item(0, 3)->setBackgroundColor(titleBackground); + table->item(0, 3)->setToolTip("This column shows the currency"); + table->item(0, 3)->setFont(titleFont); + + table->setItem(1, 3, new SpreadSheetItem("NOK")); + table->setItem(2, 3, new SpreadSheetItem("NOK")); + table->setItem(3, 3, new SpreadSheetItem("EUR")); + table->setItem(4, 3, new SpreadSheetItem("EUR")); + table->setItem(5, 3, new SpreadSheetItem("USD")); + table->setItem(6, 3, new SpreadSheetItem("USD")); + table->setItem(7, 3, new SpreadSheetItem("USD")); + table->setItem(8, 3, new SpreadSheetItem("USD")); + + table->setItem(9, 3, new SpreadSheetItem()); + table->item(9,3)->setBackgroundColor(Qt::lightGray); + + // column 4 + table->setItem(0, 4, new SpreadSheetItem("Ex. Rate")); + table->item(0, 4)->setBackgroundColor(titleBackground); + table->item(0, 4)->setToolTip("This column shows the exchange rate to NOK"); + table->item(0, 4)->setFont(titleFont); + + table->setItem(1, 4, new SpreadSheetItem("1")); + table->setItem(2, 4, new SpreadSheetItem("1")); + table->setItem(3, 4, new SpreadSheetItem("8")); + table->setItem(4, 4, new SpreadSheetItem("8")); + table->setItem(5, 4, new SpreadSheetItem("7")); + table->setItem(6, 4, new SpreadSheetItem("7")); + table->setItem(7, 4, new SpreadSheetItem("7")); + table->setItem(8, 4, new SpreadSheetItem("7")); + + table->setItem(9, 4, new SpreadSheetItem()); + table->item(9,4)->setBackgroundColor(Qt::lightGray); + + // column 5 + table->setItem(0, 5, new SpreadSheetItem("NOK")); + table->item(0, 5)->setBackgroundColor(titleBackground); + table->item(0, 5)->setToolTip("This column shows the expenses in NOK"); + table->item(0, 5)->setFont(titleFont); + + table->setItem(1, 5, new SpreadSheetItem("* C2 E2")); + table->setItem(2, 5, new SpreadSheetItem("* C3 E3")); + table->setItem(3, 5, new SpreadSheetItem("* C4 E4")); + table->setItem(4, 5, new SpreadSheetItem("* C5 E5")); + table->setItem(5, 5, new SpreadSheetItem("* C6 E6")); + table->setItem(6, 5, new SpreadSheetItem("* C7 E7")); + table->setItem(7, 5, new SpreadSheetItem("* C8 E8")); + table->setItem(8, 5, new SpreadSheetItem("* C9 E9")); + + table->setItem(9, 5, new SpreadSheetItem("sum F2 F9")); + table->item(9,5)->setBackgroundColor(Qt::lightGray); +} + +const char *htmlText = +"" +"

This demo shows use of QTableWidget with custom handling for" +" individual cells.

" +"

Using a customized table item we make it possible to have dynamic" +" output in different cells. The content that is implemented for this" +" particular demo is:" +"

    " +"
  • Adding two cells.
  • " +"
  • Subtracting one cell from another.
  • " +"
  • Multiplying two cells.
  • " +"
  • Dividing one cell with another.
  • " +"
  • Summing the contents of an arbitrary number of cells.
  • " +""; + +void SpreadSheet::showAbout() +{ + QMessageBox::about(this, "About Spreadsheet", htmlText); +} + +void decode_pos(const QString &pos, int *row, int *col) +{ + if (pos.isEmpty()) { + *col = -1; + *row = -1; + } else { + *col = pos.at(0).toLatin1() - 'A'; + *row = pos.right(pos.size() - 1).toInt() - 1; + } +} + +QString encode_pos(int row, int col) +{ + return QString(col + 'A') + QString::number(row + 1); +} + + +void SpreadSheet::print() +{ +#ifndef QT_NO_PRINTER + QPrinter printer(QPrinter::ScreenResolution); + QPrintPreviewDialog dlg(&printer); + PrintView view; + view.setModel(table->model()); + connect(&dlg, SIGNAL(paintRequested(QPrinter*)), + &view, SLOT(print(QPrinter*))); + dlg.exec(); +#endif +} + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.h b/examples/widgets/itemviews/spreadsheet/spreadsheet.h new file mode 100644 index 0000000000..d2b76c9063 --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.h @@ -0,0 +1,124 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPREADSHEET_H +#define SPREADSHEET_H + +#include + +QT_BEGIN_NAMESPACE +class QAction; +class QLabel; +class QLineEdit; +class QToolBar; +class QTableWidgetItem; +class QTableWidget; +QT_END_NAMESPACE + +class SpreadSheet : public QMainWindow +{ + Q_OBJECT + +public: + + SpreadSheet(int rows, int cols, QWidget *parent = 0); + +public slots: + void updateStatus(QTableWidgetItem *item); + void updateColor(QTableWidgetItem *item); + void updateLineEdit(QTableWidgetItem *item); + void returnPressed(); + void selectColor(); + void selectFont(); + void clear(); + void showAbout(); + + void print(); + + void actionSum(); + void actionSubtract(); + void actionAdd(); + void actionMultiply(); + void actionDivide(); + +protected: + void setupContextMenu(); + void setupContents(); + + void setupMenuBar(); + void createActions(); + + void actionMath_helper(const QString &title, const QString &op); + bool runInputDialog(const QString &title, + const QString &c1Text, + const QString &c2Text, + const QString &opText, + const QString &outText, + QString *cell1, QString *cell2, QString *outCell); +private: + QToolBar *toolBar; + QAction *colorAction; + QAction *fontAction; + QAction *firstSeparator; + QAction *cell_sumAction; + QAction *cell_addAction; + QAction *cell_subAction; + QAction *cell_mulAction; + QAction *cell_divAction; + QAction *secondSeparator; + QAction *clearAction; + QAction *aboutSpreadSheet; + QAction *exitAction; + + QAction *printAction; + + QLabel *cellLabel; + QTableWidget *table; + QLineEdit *formulaInput; + +}; + +void decode_pos(const QString &pos, int *row, int *col); +QString encode_pos(int row, int col); + + +#endif // SPREADSHEET_H + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.pro b/examples/widgets/itemviews/spreadsheet/spreadsheet.pro new file mode 100644 index 0000000000..48fd07e7fd --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.pro @@ -0,0 +1,23 @@ +QT += widgets +!isEmpty(QT.printsupport.name): QT += printsupport +#unix:contains(QT_CONFIG, dbus):QT += dbus widgets + +HEADERS += printview.h spreadsheet.h spreadsheetdelegate.h spreadsheetitem.h +SOURCES += main.cpp \ + printview.cpp \ + spreadsheet.cpp \ + spreadsheetdelegate.cpp \ + spreadsheetitem.cpp +RESOURCES += spreadsheet.qrc + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/spreadsheet +sources.files = $$SOURCES $$RESOURCES *.pro images $$HEADERS +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/spreadsheet +INSTALLS += target sources + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheet.qrc b/examples/widgets/itemviews/spreadsheet/spreadsheet.qrc new file mode 100644 index 0000000000..13f496d8e3 --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheet.qrc @@ -0,0 +1,5 @@ + + + images/interview.png + + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp new file mode 100644 index 0000000000..d5e747dc2f --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp @@ -0,0 +1,114 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spreadsheetdelegate.h" +#include + +SpreadSheetDelegate::SpreadSheetDelegate(QObject *parent) + : QItemDelegate(parent) {} + +QWidget *SpreadSheetDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem &, + const QModelIndex &index) const +{ + if (index.column() == 1) { + QDateTimeEdit *editor = new QDateTimeEdit(parent); + editor->setDisplayFormat("dd/M/yyyy"); + editor->setCalendarPopup(true); + return editor; + } + + QLineEdit *editor = new QLineEdit(parent); + + // create a completer with the strings in the column as model + QStringList allStrings; + for (int i = 1; irowCount(); i++) { + QString strItem(index.model()->data(index.sibling(i, index.column()), + Qt::EditRole).toString()); + + if (!allStrings.contains(strItem)) + allStrings.append(strItem); + } + + QCompleter *autoComplete = new QCompleter(allStrings); + editor->setCompleter(autoComplete); + connect(editor, SIGNAL(editingFinished()), + this, SLOT(commitAndCloseEditor())); + return editor; +} + +void SpreadSheetDelegate::commitAndCloseEditor() +{ + QLineEdit *editor = qobject_cast(sender()); + emit commitData(editor); + emit closeEditor(editor); +} + +void SpreadSheetDelegate::setEditorData(QWidget *editor, + const QModelIndex &index) const +{ + QLineEdit *edit = qobject_cast(editor); + if (edit) { + edit->setText(index.model()->data(index, Qt::EditRole).toString()); + } else { + QDateTimeEdit *dateEditor = qobject_cast(editor); + if (dateEditor) { + dateEditor->setDate(QDate::fromString( + index.model()->data(index, Qt::EditRole).toString(), + "d/M/yyyy")); + } + } +} + +void SpreadSheetDelegate::setModelData(QWidget *editor, + QAbstractItemModel *model, const QModelIndex &index) const +{ + QLineEdit *edit = qobject_cast(editor); + if (edit) { + model->setData(index, edit->text()); + } else { + QDateTimeEdit *dateEditor = qobject_cast(editor); + if (dateEditor) { + model->setData(index, dateEditor->date().toString("dd/M/yyyy")); + } + } +} + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h new file mode 100644 index 0000000000..3487b16ab7 --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.h @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPREADSHEETDELEGATE_H +#define SPREADSHEETDELEGATE_H + +#include +#include "spreadsheet.h" + +class SpreadSheetDelegate : public QItemDelegate +{ + Q_OBJECT + +public: + SpreadSheetDelegate(QObject *parent = 0); + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, + const QModelIndex &index) const; + void setEditorData(QWidget *editor, const QModelIndex &index) const; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const; + +private slots: + void commitAndCloseEditor(); +}; + +#endif // SPREADSHEETDELEGATE_H + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp new file mode 100644 index 0000000000..88f8afa325 --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.cpp @@ -0,0 +1,167 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spreadsheetitem.h" + +SpreadSheetItem::SpreadSheetItem() + : QTableWidgetItem(), isResolving(false) +{ +} + +SpreadSheetItem::SpreadSheetItem(const QString &text) + : QTableWidgetItem(text), isResolving(false) +{ +} + +QTableWidgetItem *SpreadSheetItem::clone() const +{ + SpreadSheetItem *item = new SpreadSheetItem(); + *item = *this; + return item; +} + +QVariant SpreadSheetItem::data(int role) const +{ + if (role == Qt::EditRole || role == Qt::StatusTipRole) + return formula(); + + if (role == Qt::DisplayRole) + return display(); + + QString t = display().toString(); + bool isNumber = false; + int number = t.toInt(&isNumber); + + if (role == Qt::TextColorRole) { + if (!isNumber) + return QVariant::fromValue(QColor(Qt::black)); + else if (number < 0) + return QVariant::fromValue(QColor(Qt::red)); + return QVariant::fromValue(QColor(Qt::blue)); + } + + if (role == Qt::TextAlignmentRole) + if (!t.isEmpty() && (t.at(0).isNumber() || t.at(0) == '-')) + return (int)(Qt::AlignRight | Qt::AlignVCenter); + + return QTableWidgetItem::data(role); + } + +void SpreadSheetItem::setData(int role, const QVariant &value) +{ + QTableWidgetItem::setData(role, value); + if (tableWidget()) + tableWidget()->viewport()->update(); +} + +QVariant SpreadSheetItem::display() const +{ + // avoid circular dependencies + if (isResolving) + return QVariant(); + + isResolving = true; + QVariant result = computeFormula(formula(), tableWidget(), this); + isResolving = false; + return result; +} + +QVariant SpreadSheetItem::computeFormula(const QString &formula, + const QTableWidget *widget, + const QTableWidgetItem *self) +{ + // check if the s tring is actually a formula or not + QStringList list = formula.split(' '); + if (list.isEmpty() || !widget) + return formula; // it is a normal string + + QString op = list.value(0).toLower(); + + int firstRow = -1; + int firstCol = -1; + int secondRow = -1; + int secondCol = -1; + + if (list.count() > 1) + decode_pos(list.value(1), &firstRow, &firstCol); + + if (list.count() > 2) + decode_pos(list.value(2), &secondRow, &secondCol); + + const QTableWidgetItem *start = widget->item(firstRow, firstCol); + const QTableWidgetItem *end = widget->item(secondRow, secondCol); + + int firstVal = start ? start->text().toInt() : 0; + int secondVal = end ? end->text().toInt() : 0; + + QVariant result; + if (op == "sum") { + int sum = 0; + for (int r = firstRow; r <= secondRow; ++r) { + for (int c = firstCol; c <= secondCol; ++c) { + const QTableWidgetItem *tableItem = widget->item(r, c); + if (tableItem && tableItem != self) + sum += tableItem->text().toInt(); + } + } + + result = sum; + } else if (op == "+") { + result = (firstVal + secondVal); + } else if (op == "-") { + result = (firstVal - secondVal); + } else if (op == "*") { + result = (firstVal * secondVal); + } else if (op == "/") { + if (secondVal == 0) + result = QString("nan"); + else + result = (firstVal / secondVal); + } else if (op == "=") { + if (start) + result = start->text(); + } else { + result = formula; + } + + return result; +} + diff --git a/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h new file mode 100644 index 0000000000..e61138c08b --- /dev/null +++ b/examples/widgets/itemviews/spreadsheet/spreadsheetitem.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** 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. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPREADSHEETITEM_H +#define SPREADSHEETITEM_H + +#include +#include +#include "spreadsheet.h" + +class SpreadSheetItem : public QTableWidgetItem +{ +public: + SpreadSheetItem(); + SpreadSheetItem(const QString &text); + + QTableWidgetItem *clone() const; + + QVariant data(int role) const; + void setData(int role, const QVariant &value); + QVariant display() const; + + inline QString formula() const + { return QTableWidgetItem::data(Qt::DisplayRole).toString(); } + + static QVariant computeFormula(const QString &formula, + const QTableWidget *widget, + const QTableWidgetItem *self = 0); + +private: + mutable bool isResolving; +}; + +#endif // SPREADSHEETITEM_H + diff --git a/examples/widgets/itemviews/stardelegate/main.cpp b/examples/widgets/itemviews/stardelegate/main.cpp new file mode 100644 index 0000000000..3c988e0a8a --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/main.cpp @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "stardelegate.h" +#include "stareditor.h" +#include "starrating.h" + +//! [0] +void populateTableWidget(QTableWidget *tableWidget) +{ + static const struct { + const char *title; + const char *genre; + const char *artist; + int rating; + } staticData[] = { +//! [0] //! [1] + { "Mass in B-Minor", "Baroque", "J.S. Bach", 5 }, +//! [1] + { "Three More Foxes", "Jazz", "Maynard Ferguson", 4 }, + { "Sex Bomb", "Pop", "Tom Jones", 3 }, + { "Barbie Girl", "Pop", "Aqua", 5 }, +//! [2] + { 0, 0, 0, 0 } +//! [2] //! [3] + }; +//! [3] //! [4] + + for (int row = 0; staticData[row].title != 0; ++row) { + QTableWidgetItem *item0 = new QTableWidgetItem(staticData[row].title); + QTableWidgetItem *item1 = new QTableWidgetItem(staticData[row].genre); + QTableWidgetItem *item2 = new QTableWidgetItem(staticData[row].artist); + QTableWidgetItem *item3 = new QTableWidgetItem; + item3->setData(0, + QVariant::fromValue(StarRating(staticData[row].rating))); + + tableWidget->setItem(row, 0, item0); + tableWidget->setItem(row, 1, item1); + tableWidget->setItem(row, 2, item2); + tableWidget->setItem(row, 3, item3); + } +} +//! [4] + +//! [5] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QTableWidget tableWidget(4, 4); + tableWidget.setItemDelegate(new StarDelegate); + tableWidget.setEditTriggers(QAbstractItemView::DoubleClicked + | QAbstractItemView::SelectedClicked); + tableWidget.setSelectionBehavior(QAbstractItemView::SelectRows); + + QStringList headerLabels; + headerLabels << "Title" << "Genre" << "Artist" << "Rating"; + tableWidget.setHorizontalHeaderLabels(headerLabels); + + populateTableWidget(&tableWidget); + + tableWidget.resizeColumnsToContents(); + tableWidget.resize(500, 300); + tableWidget.show(); + + return app.exec(); +} +//! [5] diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.cpp b/examples/widgets/itemviews/stardelegate/stardelegate.cpp new file mode 100644 index 0000000000..3032c20088 --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/stardelegate.cpp @@ -0,0 +1,129 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "stardelegate.h" +#include "stareditor.h" +#include "starrating.h" + +//! [0] +void StarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.data().canConvert()) { + StarRating starRating = qvariant_cast(index.data()); + + if (option.state & QStyle::State_Selected) + painter->fillRect(option.rect, option.palette.highlight()); + + starRating.paint(painter, option.rect, option.palette, + StarRating::ReadOnly); + } else { + QStyledItemDelegate::paint(painter, option, index); + } +//! [0] +} + +//! [1] +QSize StarDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.data().canConvert()) { + StarRating starRating = qvariant_cast(index.data()); + return starRating.sizeHint(); + } else { + return QStyledItemDelegate::sizeHint(option, index); + } +} +//! [1] + +//! [2] +QWidget *StarDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem &option, + const QModelIndex &index) const + +{ + if (index.data().canConvert()) { + StarEditor *editor = new StarEditor(parent); + connect(editor, SIGNAL(editingFinished()), + this, SLOT(commitAndCloseEditor())); + return editor; + } else { + return QStyledItemDelegate::createEditor(parent, option, index); + } +} +//! [2] + +//! [3] +void StarDelegate::setEditorData(QWidget *editor, + const QModelIndex &index) const +{ + if (index.data().canConvert()) { + StarRating starRating = qvariant_cast(index.data()); + StarEditor *starEditor = qobject_cast(editor); + starEditor->setStarRating(starRating); + } else { + QStyledItemDelegate::setEditorData(editor, index); + } +} +//! [3] + +//! [4] +void StarDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const +{ + if (index.data().canConvert()) { + StarEditor *starEditor = qobject_cast(editor); + model->setData(index, QVariant::fromValue(starEditor->starRating())); + } else { + QStyledItemDelegate::setModelData(editor, model, index); + } +} +//! [4] + +//! [5] +void StarDelegate::commitAndCloseEditor() +{ + StarEditor *editor = qobject_cast(sender()); + emit commitData(editor); + emit closeEditor(editor); +} +//! [5] diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.desktop b/examples/widgets/itemviews/stardelegate/stardelegate.desktop new file mode 100644 index 0000000000..d508c3b286 --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/stardelegate.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Star Delegate +Exec=/opt/usr/bin/stardelegate +Icon=stardelegate +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.h b/examples/widgets/itemviews/stardelegate/stardelegate.h new file mode 100644 index 0000000000..6c53ab8833 --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/stardelegate.h @@ -0,0 +1,69 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef STARDELEGATE_H +#define STARDELEGATE_H + +#include + +//! [0] +class StarDelegate : public QStyledItemDelegate +{ + Q_OBJECT + +public: + StarDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) {} + + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + QSize sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const; + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + void setEditorData(QWidget *editor, const QModelIndex &index) const; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const; + +private slots: + void commitAndCloseEditor(); +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/stardelegate/stardelegate.pro b/examples/widgets/itemviews/stardelegate/stardelegate.pro new file mode 100644 index 0000000000..915c26a524 --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/stardelegate.pro @@ -0,0 +1,17 @@ +HEADERS = stardelegate.h \ + stareditor.h \ + starrating.h +SOURCES = main.cpp \ + stardelegate.cpp \ + stareditor.cpp \ + starrating.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/stardelegate +sources.files = $$SOURCES $$HEADERS *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/itemviews/stardelegate +INSTALLS += target sources + + +QT += widgets +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/itemviews/stardelegate/stareditor.cpp b/examples/widgets/itemviews/stardelegate/stareditor.cpp new file mode 100644 index 0000000000..795a748941 --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/stareditor.cpp @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "stareditor.h" +#include "starrating.h" + +//! [0] +StarEditor::StarEditor(QWidget *parent) + : QWidget(parent) +{ + setMouseTracking(true); + setAutoFillBackground(true); +} +//! [0] + +QSize StarEditor::sizeHint() const +{ + return myStarRating.sizeHint(); +} + +//! [1] +void StarEditor::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + myStarRating.paint(&painter, rect(), this->palette(), + StarRating::Editable); +} +//! [1] + +//! [2] +void StarEditor::mouseMoveEvent(QMouseEvent *event) +{ + int star = starAtPosition(event->x()); + + if (star != myStarRating.starCount() && star != -1) { + myStarRating.setStarCount(star); + update(); + } +} +//! [2] + +//! [3] +void StarEditor::mouseReleaseEvent(QMouseEvent * /* event */) +{ + emit editingFinished(); +} +//! [3] + +//! [4] +int StarEditor::starAtPosition(int x) +{ + int star = (x / (myStarRating.sizeHint().width() + / myStarRating.maxStarCount())) + 1; + if (star <= 0 || star > myStarRating.maxStarCount()) + return -1; + + return star; +} +//! [4] diff --git a/examples/widgets/itemviews/stardelegate/stareditor.h b/examples/widgets/itemviews/stardelegate/stareditor.h new file mode 100644 index 0000000000..88bee7d28d --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/stareditor.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef STAREDITOR_H +#define STAREDITOR_H + +#include + +#include "starrating.h" + +//! [0] +class StarEditor : public QWidget +{ + Q_OBJECT + +public: + StarEditor(QWidget *parent = 0); + + QSize sizeHint() const; + void setStarRating(const StarRating &starRating) { + myStarRating = starRating; + } + StarRating starRating() { return myStarRating; } + +signals: + void editingFinished(); + +protected: + void paintEvent(QPaintEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + +private: + int starAtPosition(int x); + + StarRating myStarRating; +}; +//! [0] + +#endif diff --git a/examples/widgets/itemviews/stardelegate/starrating.cpp b/examples/widgets/itemviews/stardelegate/starrating.cpp new file mode 100644 index 0000000000..cea9330db2 --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/starrating.cpp @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +#include "starrating.h" + +const int PaintingScaleFactor = 20; + +//! [0] +StarRating::StarRating(int starCount, int maxStarCount) +{ + myStarCount = starCount; + myMaxStarCount = maxStarCount; + + starPolygon << QPointF(1.0, 0.5); + for (int i = 1; i < 5; ++i) + starPolygon << QPointF(0.5 + 0.5 * cos(0.8 * i * 3.14), + 0.5 + 0.5 * sin(0.8 * i * 3.14)); + + diamondPolygon << QPointF(0.4, 0.5) << QPointF(0.5, 0.4) + << QPointF(0.6, 0.5) << QPointF(0.5, 0.6) + << QPointF(0.4, 0.5); +} +//! [0] + +//! [1] +QSize StarRating::sizeHint() const +{ + return PaintingScaleFactor * QSize(myMaxStarCount, 1); +} +//! [1] + +//! [2] +void StarRating::paint(QPainter *painter, const QRect &rect, + const QPalette &palette, EditMode mode) const +{ + painter->save(); + + painter->setRenderHint(QPainter::Antialiasing, true); + painter->setPen(Qt::NoPen); + + if (mode == Editable) { + painter->setBrush(palette.highlight()); + } else { + painter->setBrush(palette.foreground()); + } + + int yOffset = (rect.height() - PaintingScaleFactor) / 2; + painter->translate(rect.x(), rect.y() + yOffset); + painter->scale(PaintingScaleFactor, PaintingScaleFactor); + + for (int i = 0; i < myMaxStarCount; ++i) { + if (i < myStarCount) { + painter->drawPolygon(starPolygon, Qt::WindingFill); + } else if (mode == Editable) { + painter->drawPolygon(diamondPolygon, Qt::WindingFill); + } + painter->translate(1.0, 0.0); + } + + painter->restore(); +} +//! [2] diff --git a/examples/widgets/itemviews/stardelegate/starrating.h b/examples/widgets/itemviews/stardelegate/starrating.h new file mode 100644 index 0000000000..04fae2509a --- /dev/null +++ b/examples/widgets/itemviews/stardelegate/starrating.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Nokia Corporation and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef STARRATING_H +#define STARRATING_H + +#include +#include +#include + +//! [0] +class StarRating +{ +public: + enum EditMode { Editable, ReadOnly }; + + StarRating(int starCount = 1, int maxStarCount = 5); + + void paint(QPainter *painter, const QRect &rect, + const QPalette &palette, EditMode mode) const; + QSize sizeHint() const; + int starCount() const { return myStarCount; } + int maxStarCount() const { return myMaxStarCount; } + void setStarCount(int starCount) { myStarCount = starCount; } + void setMaxStarCount(int maxStarCount) { myMaxStarCount = maxStarCount; } + +private: + QPolygonF starPolygon; + QPolygonF diamondPolygon; + int myStarCount; + int myMaxStarCount; +}; +//! [0] + +//! [1] +Q_DECLARE_METATYPE(StarRating) +//! [1] + +#endif -- cgit v1.2.3