void beginInsertRows(const QModelIndex &parent, int first, int last)
insertRows 方法是指定开始索引 ,然后连续加入多少个元素,而 beginInsertRows 方法是你插入元素后,它们在列表中的开始索引和结束索引。如 A、B、C,在B处插入两个元素。开始索引是 1,结束索引是 2,即结束索引的计算方法是: endIndex = startIndex + count -1。插入元素结束后必须调用 endInsertRows 方法。这一对方法的作用是让用户界面上的视图(如 QListView、QTableView 等)能及时做出响应。
同理,在删除元素时,beginRemoveRows 和 endRemoveRows 方法也必须调用。beginRemoveRows 方法的参数与 beginInsertRows 方法一样,也是索引的起止值。即要删除元素的起始索引,和被删除的最后一个元素的索引。如1、2、3、4,要删除2、3、4,那么起始索引是 1,结束索引 3。
int main(int argc, char** argv)
{
QApplication myapp(argc, argv);
// 窗口
QWidget *window = new QWidget;
// 布局
QGridLayout *layout = new QGridLayout;
window->setLayout(layout);
// 列表视图
QListView* view = new QListView(window);
// 实例化模型
CustListModel* model = new CustListModel(window);
// 设置到视图中
view->setModel(model);
layout->addWidget(view, 0, 0, 3, 1);
// 按钮
QPushButton* btnAdd=new QPushButton("新增", window);
QPushButton* btnDel = new QPushButton("移除", window);
QPushButton* btnShowAll = new QPushButton("显示列表", window);
layout->addWidget(btnAdd, 0, 1);
layout->addWidget(btnDel, 1, 1);
layout->addWidget(btnShowAll, 2, 1);
layout->setColumnStretch(0, 1);
// 连接clicked信号
QObject::connect(
btnAdd,
&QPushButton::clicked,
[&view, &model, &window]()
{
bool res;
int val = QInputDialog::getInt(
window, //父窗口
"输入", //窗口标题
"请输入整数:", //提示文本
0, //默认值
0, //最小值
1000, //最大值
1, //步长值
&res //表示操作结果
);
if(!res)
return;
// 索引为count
int i = model->rowCount();
// 添加一项
model->insertRow(i);
// 获取新索引
QModelIndex newIndex = model->index(i);
// 设置此项的值
model->setData(newIndex, QVariant(val), Qt::DisplayRole);
}
);
QObject::connect(
btnDel,
&QPushButton::clicked,
[&window, &view, &model]()
{
// 当前项
QModelIndex curri = view->currentIndex();
if(!curri.isValid())
return;
// 删除
model->removeRow(curri.row());
}
);
QObject::connect(
btnShowAll,
&QPushButton::clicked,
[&model, &window]()
{
// 获取总数
int c = model->rowCount();
QString msg;
for(int x = 0; x < c; x++)
{
// 获取值
QVariant value = model->data(model->index(x), Qt::DisplayRole);
if(value.isValid())
{
int n = qvariant_cast<int>(value);
msg += QString(" %1").arg(n);
}
}
QMessageBox::information(window,"提示",msg);
}
);
// 标题
window->setWindowTitle("小型列表");
// 显示
window->show();
return QApplication::exec();
}
“新增”按钮被点击后,先通过 QInputDialog.getInt 静态方法,弹出一个输入内容的对话框,然后把输入的值添加到模型中。模型中添加元素用的就是 insertRow 方法——只插入一个元素,它调用了咱们上面实现的 insertRows 方法,只是把 count 参数设置为 1。这里我实现的是新元素总是追加在列表最后,即新元素的行号等于 rowCount。
删除元素时,QListView 组件的 currentIndex 方法返回当前选中项的索引。在单选模式下,99.9% 被选中的项是等同于当前项的。多选模式下就不好说了,所以,如果需要,