SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
P R A C T IC A L M O D EL V IEW
PR O GR A M M IN G
C O D E LESS . V I EW M O R E.
Marius Bugge Monsen,
MSc (N TN U),
Software D eveloper
C ontents

●   An O verview of the Q t Model View Architecture
●   An Introduction to The Model Interface
●   Advanced Model View Techniques (Q t 4.1+)
A n O verview of the Q t M odel V iew A rchitecture
I tem S elections



         U ser I nput                        I tem Selection State




                            U ser I nput
       V iew                                       I tem D elegate




C hange N otif cations
             i                                D ata C hanges




                              M odel
Item B ased V iews (Q t 3 and 4)


Table W idget    T ree W idget    List W idget
I tem S elections




V iew                       V iew




             M odel
int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  QDirModel model;
  QTableView view1;
  QTreeView view2;

    view1.setModel(&model);
    view2.setModel(&model);

    view1.setRootIndex(model.index(0, 0));
    view1.show();
    view2.show();
    app.exec();
}
W hat do you get ?

    Eff ciency
      i
    Flexibility
   Maintainability
A n I ntroduction To T he M odel Interface
class ListModel : public QAbstractListModel
{
   Q_OBJECT
public:
   ListModel(QObject *parent = 0);
   ~ListModel();

     int rowCount(const QModelIndex &parent) const;
     QVariant data(const QModelIndex &index, int role) const;
};
ListModel::ListModel(QObject *parent)
   : QAbstractListModel(parent) {}
ListModel::~ListModel() {}

int ListModel::rowCount(const QModelIndex &) const
{
   return 10000;
}

QVariant ListModel::data(const QModelIndex &index,
                          int role) const
{
   if (role == Qt::DisplayRole)
      return index.row();
   return QVariant();
}
0       0   1   2

0       0


1       1

2       2
int main(int, char *[])
{
   ListModel model;

    QModelIndex index = model.index(2);
    QVariant data = model.data(index, Qt::DisplayRole);

    qDebug() << data;
}
D ecoration R ole
                            Type:Image File
                            Size: 1.2 Mb



                                        ToolT ip R ole

                    M y W orld


D isplay R ole
QVariant ListModel::data(const QModelIndex &index,
                          int role) const
{
   if (role == Qt::DisplayRole)
      return index.row();

    if (role == Qt::DecorationRole)
       return QColor(Qt::green);

    return QVariant();
}
class ColorDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    ColorDelegate(QObject *parent = 0);
protected:
    void paint(QPainter *painter,
               const QStyleOptionViewItem &option,
               const QModelIndex &index) const;
};
void ColorDelegate::paint(QPainter *painter,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
{
    const QAbstractItemModel *model = index.model();
    QVariant decoration = model->data(index, Qt::DecorationRole);
    if (decoration.type() == QVariant::Color) {
        QLinearGradient gradient(option.rect.left(), 0,
                                 option.rect.width(), 0);
        QColor left = option.palette.color(QPalette::Background);
        gradient.setColorAt(0, left);
        QColor right = qvariant_cast<QColor>(decoration);
        gradient.setColorAt(1, right);
        painter->fillRect(option.rect, gradient);
    }
    QItemDelegate::paint(painter, option, index);
}
One     100   -300   500
Two     599   300    233
Three   33    -34    -55
Four    200   502    200
class TableModel : public QAbstractTableModel
{
   Q_OBJECT
public:
   TableModel(QObject *parent = 0);
   ~TableModel();
   int rowCount(const QModelIndex &parent) const;
   int columnCount(const QModelIndex &parent) const;
   QVariant data(const QModelIndex &index, int role) const;
   bool setData(const QModelIndex &index,
                const QVariant &value, int role);
   Qt::ItemFlags flags(const QModelIndex &index) const;
   // not part of the model interface
   bool load(const QString &fileName);
   bool save(const QString &fileName) const;
private:
   int rows, columns;
   QVector<QVariant> table;
};
QVariant TableModel::data(const QModelIndex &index,
                          int role) const
{
   int i = index.row() * columns + index.column();
   QVariant value = table.at(i);

    if (role == Qt::EditRole || role == Qt::DisplayRole)
       return value;

    if (role == Qt::TextColorRole
       && value.type() == QVariant::Int) {
    if (value.toInt() < 0)
       return QColor(Qt::red);
       return QColor(Qt::blue);
    }
    return QVariant();
}
bool TableModel::setData(const QModelIndex &index,
                     const QVariant &value, int role)
{
   int i = index.row() * columns + index.column();
   if (role == Qt::EditRole) {
      table[i] = value;
      QModelIndex topLeft = index;
      QModelIndex bottomRight = index;
      emit dataChanged(topLeft, bottomRight);// <<< important!
      return true;
   }
   return false;
}
Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
   return QAbstractTableModel::flags(index)|Qt::ItemIsEditable;
}
bool TableModel::load(const QString &fileName)
{
   QFile file(fileName);
   if (!file.open(QIODevice::ReadOnly|QIODevice::Text))
      return false;
   rows = columns = 0;
   table.clear();
   QTextStream in(&file);
   bool result = parse(in);

    reset();// <<< important!

    return result;
}
A dvanced M odel V iew Techniques (Q t 4.1+)
M odel   P roxy   V iew
M odel   S orting   V iew
int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   TableModel model;
   model.load("table.data");

    QSortingProxyModel sorter;
    sorter.setSourceModel(&model);
    QTreeView treeview;
    treeview.setModel(&sorter);

    treeview.header()->setClickable(true);
    treeview.header()->setSortIndicatorShown(true);
    treeview.show();
    return app.exec();
}
M odel   Filtering   V iew
int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   QWidget widget;
   QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom,
                                        &widget);
   QLineEdit *lineedit = new QLineEdit;
   layout->addWidget(lineedit);
   TableModel model;
   model.load("table.data");
   QStringFilterModel filter;
   filter.setSourceModel(&model);
   QObject::connect(lineedit,SIGNAL(textChanged(const QString&)),
                    &filter,SLOT(setPattern(const QString&)));
   QTableView *tableview = new QTableView;
   tableview->setModel(&filter);
   layout->addWidget(tableview);
   widget.show();
   return app.exec();
}
M odel
  1


         A gg regating   V iew
M odel
  2
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QTreeView treeview;
    QStringListModel model_1(QStringList()
                             << "ALPHA" << "BRAVO"
                             << "CHARLIE" << "DELTA");
    QDirModel model_2;
    QAggregatingProxyModel aggregator;
    aggregator.appendSourceModel(&model_1);
    aggregator.appendSourceModel(&model_2);
    treeview.setModel(&aggregator);
    treeview.show();
    return app.exec();
}
W hat we have covered

●   Q t Model View Architecture O verview
●   The Model Interface Introduction
●   Advanced Techniques Using the Model Interface
M ore Inform ation


http://doc.trolltech.com/4.0/model-view-programming.html
http://doc.trolltech.com/4.0/model-view.html

Weitere ähnliche Inhalte

Was ist angesagt?

QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentICS
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and GraphicsAndreas Jakl
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
Svcc Java2D And Groovy
Svcc Java2D And GroovySvcc Java2D And Groovy
Svcc Java2D And GroovyAndres Almiray
 
Recoil at Codete Webinars #3
Recoil at Codete Webinars #3Recoil at Codete Webinars #3
Recoil at Codete Webinars #3Mateusz Bryła
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIICS
 
Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsJussi Pohjolainen
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinIain Hull
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinJorge Ortiz
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friendThe Software House
 

Was ist angesagt? (20)

QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
Qt Animation
Qt AnimationQt Animation
Qt Animation
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
Svcc Java2D And Groovy
Svcc Java2D And GroovySvcc Java2D And Groovy
Svcc Java2D And Groovy
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 
Recoil at Codete Webinars #3
Recoil at Codete Webinars #3Recoil at Codete Webinars #3
Recoil at Codete Webinars #3
 
Treinamento Qt básico - aula III
Treinamento Qt básico - aula IIITreinamento Qt básico - aula III
Treinamento Qt básico - aula III
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and Slots
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
OpenVG 1.1 Reference Card
OpenVG 1.1 Reference Card OpenVG 1.1 Reference Card
OpenVG 1.1 Reference Card
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con Berlin
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & Kotlin
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 

Andere mochten auch

Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Applicationaccount inactive
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutAudrey Roy
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 

Andere mochten auch (7)

IPC with Qt
IPC with QtIPC with Qt
IPC with Qt
 
Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Application
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Python Worst Practices
Python Worst PracticesPython Worst Practices
Python Worst Practices
 

Ähnlich wie Practical Model View Programming

Integrazione QML / C++
Integrazione QML / C++Integrazione QML / C++
Integrazione QML / C++Paolo Sereno
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and AnalysisWiwat Ruengmee
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 
The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210Mahmoud Samir Fayed
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4ICS
 
삼성 바다 앱개발 실패 노하우 2부
삼성 바다 앱개발 실패 노하우 2부삼성 바다 앱개발 실패 노하우 2부
삼성 바다 앱개발 실패 노하우 2부mosaicnet
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfbermanbeancolungak45
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 

Ähnlich wie Practical Model View Programming (20)

Integrazione QML / C++
Integrazione QML / C++Integrazione QML / C++
Integrazione QML / C++
 
The STL
The STLThe STL
The STL
 
Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Pointcuts and Analysis
Pointcuts and AnalysisPointcuts and Analysis
Pointcuts and Analysis
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Bw14
Bw14Bw14
Bw14
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4
 
삼성 바다 앱개발 실패 노하우 2부
삼성 바다 앱개발 실패 노하우 2부삼성 바다 앱개발 실패 노하우 2부
삼성 바다 앱개발 실패 노하우 2부
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdf
 
Functional C++
Functional C++Functional C++
Functional C++
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 

Mehr von Marius Bugge Monsen

The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...Marius Bugge Monsen
 
How to hire and keep good people
How to hire and keep good peopleHow to hire and keep good people
How to hire and keep good peopleMarius Bugge Monsen
 
Qt Itemviews, The Next Generation
Qt Itemviews, The Next GenerationQt Itemviews, The Next Generation
Qt Itemviews, The Next GenerationMarius Bugge Monsen
 
Qt Itemviews, The Next Generation (Bossa09)
Qt Itemviews, The Next Generation (Bossa09)Qt Itemviews, The Next Generation (Bossa09)
Qt Itemviews, The Next Generation (Bossa09)Marius Bugge Monsen
 

Mehr von Marius Bugge Monsen (8)

The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
The Anatomy of Real World Apps - Dissecting cross-platform apps written using...
 
About Cutehacks
About CutehacksAbout Cutehacks
About Cutehacks
 
How to hire and keep good people
How to hire and keep good peopleHow to hire and keep good people
How to hire and keep good people
 
I can see your house from here
I can see your house from hereI can see your house from here
I can see your house from here
 
The Qt 4 Item Views
The Qt 4 Item ViewsThe Qt 4 Item Views
The Qt 4 Item Views
 
Qt Widgets In Depth
Qt Widgets In DepthQt Widgets In Depth
Qt Widgets In Depth
 
Qt Itemviews, The Next Generation
Qt Itemviews, The Next GenerationQt Itemviews, The Next Generation
Qt Itemviews, The Next Generation
 
Qt Itemviews, The Next Generation (Bossa09)
Qt Itemviews, The Next Generation (Bossa09)Qt Itemviews, The Next Generation (Bossa09)
Qt Itemviews, The Next Generation (Bossa09)
 

Practical Model View Programming

  • 1. P R A C T IC A L M O D EL V IEW PR O GR A M M IN G C O D E LESS . V I EW M O R E.
  • 2. Marius Bugge Monsen, MSc (N TN U), Software D eveloper
  • 3. C ontents ● An O verview of the Q t Model View Architecture ● An Introduction to The Model Interface ● Advanced Model View Techniques (Q t 4.1+)
  • 4. A n O verview of the Q t M odel V iew A rchitecture
  • 5.
  • 6. I tem S elections U ser I nput I tem Selection State U ser I nput V iew I tem D elegate C hange N otif cations i D ata C hanges M odel
  • 7. Item B ased V iews (Q t 3 and 4) Table W idget T ree W idget List W idget
  • 8. I tem S elections V iew V iew M odel
  • 9. int main(int argc, char *argv[]) { QApplication app(argc, argv); QDirModel model; QTableView view1; QTreeView view2; view1.setModel(&model); view2.setModel(&model); view1.setRootIndex(model.index(0, 0)); view1.show(); view2.show(); app.exec(); }
  • 10.
  • 11. W hat do you get ? Eff ciency i Flexibility Maintainability
  • 12. A n I ntroduction To T he M odel Interface
  • 13. class ListModel : public QAbstractListModel { Q_OBJECT public: ListModel(QObject *parent = 0); ~ListModel(); int rowCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; };
  • 14. ListModel::ListModel(QObject *parent) : QAbstractListModel(parent) {} ListModel::~ListModel() {} int ListModel::rowCount(const QModelIndex &) const { return 10000; } QVariant ListModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) return index.row(); return QVariant(); }
  • 15.
  • 16. 0 0 1 2 0 0 1 1 2 2
  • 17.
  • 18. int main(int, char *[]) { ListModel model; QModelIndex index = model.index(2); QVariant data = model.data(index, Qt::DisplayRole); qDebug() << data; }
  • 19. D ecoration R ole Type:Image File Size: 1.2 Mb ToolT ip R ole M y W orld D isplay R ole
  • 20. QVariant ListModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) return index.row(); if (role == Qt::DecorationRole) return QColor(Qt::green); return QVariant(); }
  • 21.
  • 22. class ColorDelegate : public QItemDelegate { Q_OBJECT public: ColorDelegate(QObject *parent = 0); protected: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; };
  • 23. void ColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QAbstractItemModel *model = index.model(); QVariant decoration = model->data(index, Qt::DecorationRole); if (decoration.type() == QVariant::Color) { QLinearGradient gradient(option.rect.left(), 0, option.rect.width(), 0); QColor left = option.palette.color(QPalette::Background); gradient.setColorAt(0, left); QColor right = qvariant_cast<QColor>(decoration); gradient.setColorAt(1, right); painter->fillRect(option.rect, gradient); } QItemDelegate::paint(painter, option, index); }
  • 24.
  • 25. One 100 -300 500 Two 599 300 233 Three 33 -34 -55 Four 200 502 200
  • 26. class TableModel : public QAbstractTableModel { Q_OBJECT public: TableModel(QObject *parent = 0); ~TableModel(); int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &index, const QVariant &value, int role); Qt::ItemFlags flags(const QModelIndex &index) const; // not part of the model interface bool load(const QString &fileName); bool save(const QString &fileName) const; private: int rows, columns; QVector<QVariant> table; };
  • 27. QVariant TableModel::data(const QModelIndex &index, int role) const { int i = index.row() * columns + index.column(); QVariant value = table.at(i); if (role == Qt::EditRole || role == Qt::DisplayRole) return value; if (role == Qt::TextColorRole && value.type() == QVariant::Int) { if (value.toInt() < 0) return QColor(Qt::red); return QColor(Qt::blue); } return QVariant(); }
  • 28. bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role) { int i = index.row() * columns + index.column(); if (role == Qt::EditRole) { table[i] = value; QModelIndex topLeft = index; QModelIndex bottomRight = index; emit dataChanged(topLeft, bottomRight);// <<< important! return true; } return false; } Qt::ItemFlags TableModel::flags(const QModelIndex &index) const { return QAbstractTableModel::flags(index)|Qt::ItemIsEditable; }
  • 29. bool TableModel::load(const QString &fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) return false; rows = columns = 0; table.clear(); QTextStream in(&file); bool result = parse(in); reset();// <<< important! return result; }
  • 30.
  • 31. A dvanced M odel V iew Techniques (Q t 4.1+)
  • 32. M odel P roxy V iew
  • 33. M odel S orting V iew
  • 34. int main(int argc, char *argv[]) { QApplication app(argc, argv); TableModel model; model.load("table.data"); QSortingProxyModel sorter; sorter.setSourceModel(&model); QTreeView treeview; treeview.setModel(&sorter); treeview.header()->setClickable(true); treeview.header()->setSortIndicatorShown(true); treeview.show(); return app.exec(); }
  • 35.
  • 36. M odel Filtering V iew
  • 37. int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget widget; QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, &widget); QLineEdit *lineedit = new QLineEdit; layout->addWidget(lineedit); TableModel model; model.load("table.data"); QStringFilterModel filter; filter.setSourceModel(&model); QObject::connect(lineedit,SIGNAL(textChanged(const QString&)), &filter,SLOT(setPattern(const QString&))); QTableView *tableview = new QTableView; tableview->setModel(&filter); layout->addWidget(tableview); widget.show(); return app.exec(); }
  • 38.
  • 39. M odel 1 A gg regating V iew M odel 2
  • 40. int main(int argc, char *argv[]) { QApplication app(argc, argv); QTreeView treeview; QStringListModel model_1(QStringList() << "ALPHA" << "BRAVO" << "CHARLIE" << "DELTA"); QDirModel model_2; QAggregatingProxyModel aggregator; aggregator.appendSourceModel(&model_1); aggregator.appendSourceModel(&model_2); treeview.setModel(&aggregator); treeview.show(); return app.exec(); }
  • 41.
  • 42. W hat we have covered ● Q t Model View Architecture O verview ● The Model Interface Introduction ● Advanced Techniques Using the Model Interface
  • 43. M ore Inform ation http://doc.trolltech.com/4.0/model-view-programming.html http://doc.trolltech.com/4.0/model-view.html