QListView的使用
Posted 宋世鹏宇宙信息
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QListView的使用相关的知识,希望对你有一定的参考价值。
QListView与QTreeView一样,也是采取的mvc模式,添加数据时,用相应的模式
1、初始化时添加数据
QStandardItemModel *model = new QStandardItemModel(this); //可以把这行放到头文件里面
QStandardItem *item = new QStandardItem("item1");
model->appendRow(item);
item = new QStandardItem("item2");
model->appendRow(item);
ui->listViewTask->setModel(model);
2、根据用户操作来添加数据
QStandardItem *item = new QStandardItem("item3");
QStandardItemModel *model = dynamic_cast<QStandardItemModel*>(ui->listViewTask->model());
model->appendRow(item);
3、删除数据
QStandardItemModel *model = dynamic_cast<QStandardItemModel*>(ui->listViewTask->model());
model->removeRow(ui->listViewTask->currentIndex().row());
4.获取行数;
int row_num = ui->listViewTask->model()->rowCount();
5.选中指定的行号
QModelIndex qindex = m_listviewmodel_->index(index,0); //默认选中 index
ui->listViewTask->setCurrentIndex(qindex);
6.设置滚动方式
enum QAbstractItemView::ScrollMode
Constant Value Description
QAbstractItemView::ScrollPerItem 0 The view will scroll the contents one item at a time.
QAbstractItemView::ScrollPerPixel 1 The view will scroll the contents one pixel at a time.
//设置为像素滚动;
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
7.初始化并设置隔行彩色显示;
- standardItemModel = new QStandardItemModel(this);
- QStringList strList;
- strList.append("string1");
- strList.append("string2");
- strList.append("string3");
- strList.append("string4");
- strList.append("string5");
- strList.append("string6");
- strList.append("string7");
- strList << "string8";
- strList += "string9";
- int nCount = strList.size();
- for(int i = 0; i < nCount; i++)
- {
- QString string = static_cast<QString>(strList.at(i));
- QStandardItem *item = new QStandardItem(string);
- if(i % 2 == 1)
- {
- 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);
- }
- listView->setModel(standardItemModel);
- listView->setFixedSize(200,300);
- connect(listView,SIGNAL(clicked(QModelIndex)),this,SLOT(itemClicked(QModelIndex)));
- }
8。更新某一行;
int row=listview->currentIndex().row();
if(row!=-1)
{
QModelIndex index=listmodel->index(row);
QString str=listmodel->data(index,Qt::DisplayRole).toString();//get data
bool ok;
QString text = QInputDialog::getText(this, tr("edit item"),
tr("please edit item"), QLineEdit::Normal,
str, &ok);
if (ok && !text.isEmpty())
{
listmodel->setData(index,text,Qt::EditRole);
listview->setCurrentIndex(index);
}
}
else
{
QMessageBox::information(NULL,tr("information"),tr("please select a item"));
}
以上是关于QListView的使用的主要内容,如果未能解决你的问题,请参考以下文章
在带有 QSqlQueryModel 的 QListView 上使用 QStyledItemDelegate
QListView 与 CustomWIdget 使用 QStyledItemDelegate