#ifndef LISTVIEWSTANDARD_H #define LISTVIEWSTANDARD_H #include <QtGui/QWidget> #include <QListView> #include <QStandardItemModel> class listviewStandard : public QWidget { Q_OBJECT public: listviewStandard(QWidget *parent = 0); ~listviewStandard(); public slots: void addToModel(); void displayModel(); void delModel(QModelIndex index); private: QListView *listView; QStandardItemModel *standardItemModel; }; #endif // LISTVIEWSTANDARD_H
#include "listviewstandard.h" #include <QPushButton> #include <QGridLayout> #include <QDebug> listviewStandard::listviewStandard(QWidget *parent) : QWidget(parent) { resize(500,700); listView = new QListView(this); standardItemModel = new QStandardItemModel(this); listView->setModel(standardItemModel); listView->setFixedSize(200,300); connect(listView,SIGNAL(clicked(QModelIndex)),this,SLOT(delModel(QModelIndex))); QPushButton *ptnAdd=new QPushButton("Add"); QPushButton *ptnDel=new QPushButton("Del"); QPushButton *ptnDisplay=new QPushButton("Display"); connect(ptnAdd,SIGNAL(clicked()),this, SLOT(addToModel())); connect(ptnDisplay,SIGNAL(clicked()),this,SLOT(displayModel())); QGridLayout *winGrid=new QGridLayout; winGrid->addWidget(ptnAdd); winGrid->addWidget(ptnDel); winGrid->addWidget(ptnDisplay); setLayout(winGrid); } listviewStandard::~listviewStandard() { } void listviewStandard::addToModel() { QString string("add to model") ; QStandardItem *item = new QStandardItem(string); { QLinearGradient linearGrad(QPointF(0, 0), QPointF(200, 200)); linearGrad.setColorAt(0, Qt::darkGreen); linearGrad.setColorAt(1, Qt::yellow); QBrush brush(linearGrad); item->setBackground(brush); } standardItemModel->appendRow(item); } void listviewStandard::displayModel() { QList<QStandardItem*> list =standardItemModel->findItems("*", Qt::MatchWildcard | Qt::MatchRecursive);//查找model中的Item, foreach (QStandardItem* item, list) { qDebug() << item->text(); } } void listviewStandard::delModel(QModelIndex index) { standardItemModel->removeRows(index.row(),1); //如果是按钮的话,standardItemModel->removeRows(listview->currentIndex().row(),1); }
#include <QtGui/QApplication> #include "listviewstandard.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); listviewStandard w; w.show(); return a.exec(); }