功能简介
简单的对listview中的列表进行增删及过滤搜索后listview中显示符合条件的条目,运行截图如下:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/947dcb8e9c000969545b523309630757.png#pic_center)
完整头文件
#ifndef LISTSEARCHDIALOG_H
#define LISTSEARCHDIALOG_H
#include <QDialog>
#include <QStringList>
#include <QStringListModel>
QT_BEGIN_NAMESPACE
namespace Ui { class ListSearchDialog; }
QT_END_NAMESPACE
class ListSearchDialog : public QDialog
{
Q_OBJECT
public:
ListSearchDialog(QWidget *parent = nullptr);
~ListSearchDialog();
public:
void initFileText();
private slots:
void on_addButton_clicked();
void on_pushButton_clicked();
void on_searchButton_clicked();
private:
Ui::ListSearchDialog *ui;
QStringListModel *listShowModel;
QStringList initTextList;
};
#endif
完整源文件
#include "listsearchdialog.h"
#include "ui_listsearchdialog.h"
ListSearchDialog::ListSearchDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::ListSearchDialog)
{
ui->setupUi(this);
listShowModel = new QStringListModel(this);
initFileText();
}
ListSearchDialog::~ListSearchDialog()
{
delete ui;
}
void ListSearchDialog::initFileText()
{
initTextList<<"老街.mp3"<<"FORK LOVE.wav"<<"street.png"<<"helloPic.jpg"
<<"MYLOVE"<<"123456.mp4";
listShowModel->setStringList(initTextList);
ui->listView->setModel(listShowModel);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
void ListSearchDialog::on_addButton_clicked()
{
initTextList.append(ui->inputLineEdit->text());
int insertRow = listShowModel->rowCount();
listShowModel->insertRow(insertRow);
QModelIndex addIndex = listShowModel->index(insertRow);
listShowModel->setData(addIndex, ui->inputLineEdit->text(), Qt::DisplayRole);
}
void ListSearchDialog::on_pushButton_clicked()
{
QModelIndex curIndex = ui->listView->currentIndex();
QString removeStr = listShowModel->data(curIndex, Qt::DisplayRole).toString();
listShowModel->removeRow(curIndex.row());
initTextList.removeOne(removeStr);
}
void ListSearchDialog::on_searchButton_clicked()
{
QString searchStr = ui->searchLineEdit->text();
#if 1
QStringList newModelStr;
foreach (QString tmpStr, initTextList) {
if (tmpStr.contains(searchStr, Qt::CaseInsensitive)) {
newModelStr.append(tmpStr);
} else {
continue;
}
}
listShowModel->setStringList(newModelStr);
ui->listView->setModel(listShowModel);
#endif
#if 0
QStringList allViewText = listShowModel->stringList();
int index = 0;
for (QString txtStr : allViewText) {
if (txtStr.contains(searchStr, Qt::CaseInsensitive)) {
ui->listView->setRowHidden(index, false);
} else {
ui->listView->setRowHidden(index, true);
}
index++;
}
#endif
}
界面文件
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a4601c34aa99f2c124e778d5b39f7e9d.png#pic_center)