tableWidget搜索筛选功能

tableWidget搜索筛选功能

本想直接在CSDN上搜现成的按关键字搜索功能,无奈没找到合适的,只能自己实现一把,没找到合适的同学可以参考一下

下面代码片段可直接全部放入搜索按钮的槽函数

// ui->sousuo->text() 为lineEdit搜索框内的输入内容  下面的同理
if (ui->sousuo->text() == "")
{
     for (int i =0; i<20;i++) // 这里的20代表tableWidget的总行数,可根据自己情况换掉
     {
          ui->tableWidget->setRowHidden(i, false); // 显示第i行
      }
     return;
}
int b[20] = {0};  // 命名比较随意
int tm =0;  // 命名比较随意
for (int i = 0 ;i <20; i ++) // 这里的20代表tableWidget的总行数,可根据自己情况换掉
{
     int count =0;
     for (int j = 0; j<5;j++)  // 这里的5代表tableWidget的总列数,可根据自己情况换掉
     {
          if (ui->sousuo->text() == ui->tableWidget->item(i,j)->text())
          {
                count++;
                continue;
           }
      }
      if (count == 0) 
      {
           b[tm]= i;
           tm++;
      }
}
for (int i =0; i<tm;i++)
{
     ui->tableWidget->setRowHidden(b[i], true); // 隐藏第i行
}

实现效果口头描述一下:

搜索关键字输入到lineEdit后,按下搜索按钮,将每一行内有该关键字的行数全部show出来,没有该关键字的全都隐藏。

QtTableWidget 中,可以使用 QHeaderView 类来实现表头的筛选过滤功能。具体实现步骤如下: 1. 创建 TableWidget,添加表头。 2. 将 TableWidget 的 horizontalHeader() 设置为 QHeaderView,并设置 QHeaderView 的筛选器属性为可筛选。 3. 监听 QHeaderView 的 sectionClicked() 信号,获取点击的列号。 4. 在 sectionClicked() 信号槽中,使用 QInputDialog::getText() 获取用户输入的筛选条件。 5. 根据用户输入的条件,使用 TableWidget 的 setItemHidden() 方法来隐藏不符合条件的行。 下面是一个简单的示例代码: ``` // 创建 TableWidget,添加表头 QTableWidget *tableWidget = new QTableWidget(this); tableWidget->setColumnCount(3); tableWidget->setHorizontalHeaderLabels(QStringList() << "Name" << "Age" << "Gender"); // 设置表头为 QHeaderView,并设置为可筛选 QHeaderView *headerView = tableWidget->horizontalHeader(); headerView->setSectionsClickable(true); headerView->setSectionResizeMode(QHeaderView::Stretch); headerView->setSortIndicatorShown(true); headerView->setSortIndicator(0, Qt::AscendingOrder); headerView->setFilters(QHeaderView::Clickable | QHeaderView::TextFilter); // 监听 sectionClicked() 信号,获取点击的列号 connect(headerView, &QHeaderView::sectionClicked, [=](int logicalIndex){ // 获取用户输入的筛选条件 QString filterText = QInputDialog::getText(this, "Filter", "Enter filter text:"); // 遍历所有行,根据条件来隐藏/显示行 for (int i = 0; i < tableWidget->rowCount(); i++) { QTableWidgetItem *item = tableWidget->item(i, logicalIndex); if (item) { bool match = item->text().contains(filterText, Qt::CaseInsensitive); tableWidget->setRowHidden(i, !match); } } }); ``` 以上代码可以实现一个简单的表头筛选功能。需要注意的是,该示例中只对单列进行筛选,如果需要对多列进行筛选,需要稍作修改。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

All In !!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值