用c语言在QT上实现qtablewidget右击表头进行筛选
时间: 2024-05-04 18:20:19 浏览: 126
QTableWidget设置表头筛选(含鼠标点击事件过滤)
5星 · 资源好评率100%
可以通过以下步骤在QT上实现qtablewidget右击表头进行筛选:
1.为QTableWidget设置右键菜单:
```c++
QMenu *menu = new QMenu(ui->tableWidget);
ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->tableWidget->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->tableWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
```
2.在showMenu()函数中创建菜单项,并连接槽函数:
```c++
void MainWindow::showMenu(QPoint pos)
{
QPoint globalPos = ui->tableWidget->mapToGlobal(pos);
QMenu *menu = new QMenu(this);
QAction *filterAction = new QAction(tr("Filter"), this);
connect(filterAction, SIGNAL(triggered()), this, SLOT(showFilterDialog()));
menu->addAction(filterAction);
menu->popup(globalPos);
}
```
3.在showFilterDialog()函数中创建筛选对话框,并执行筛选操作:
```c++
void MainWindow::showFilterDialog()
{
QDialog *dialog = new QDialog(this);
QVBoxLayout *layout = new QVBoxLayout(dialog);
QComboBox *columnCombo = new QComboBox(dialog);
QLineEdit *filterEdit = new QLineEdit(dialog);
QPushButton *okButton = new QPushButton(tr("OK"), dialog);
layout->addWidget(columnCombo);
layout->addWidget(filterEdit);
layout->addWidget(okButton);
dialog->setLayout(layout);
dialog->setWindowTitle(tr("Filter"));
dialog->setModal(true);
connect(okButton, SIGNAL(clicked()), dialog, SLOT(accept()));
if(dialog->exec() == QDialog::Accepted)
{
QString filterString = filterEdit->text();
int column = columnCombo->currentIndex();
QTableWidget *tableWidget = ui->tableWidget;
for(int i = 0; i < tableWidget->rowCount(); i++)
{
QTableWidgetItem *item = tableWidget->item(i, column);
if(item)
{
if(item->text().contains(filterString, Qt::CaseInsensitive))
{
tableWidget->showRow(i);
}
else
{
tableWidget->hideRow(i);
}
}
}
}
}
```
以上就是在QT上实现qtablewidget右击表头进行筛选的方法,希望对你有所帮助。
阅读全文