c语言,用QT实现qtablewidget点击表头排序
时间: 2023-06-16 08:03:42 浏览: 245
QT-qtablewidget表头添加复选框QHeaderView
可以通过以下步骤在QT中实现QTableWidget的点击表头排序:
1. 在QT Designer中将QTableWidget添加到窗口中。
2. 在代码中为QTableWidget设置表头,并设置表头的单击信号连接到槽函数中。
```c++
QTableWidget *tableWidget = new QTableWidget(this);
tableWidget->setColumnCount(3);
tableWidget->setHorizontalHeaderLabels(QStringList() << "Name" << "Age" << "City");
connect(tableWidget->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(sortTable(int)));
```
3. 编写槽函数sortTable(),该函数根据点击的表头排序QTableWidget中的数据。
```c++
void MainWindow::sortTable(int column)
{
tableWidget->sortByColumn(column);
}
```
4. 运行程序,单击表头即可按照点击的列排序。
完整的代码如下:
```c++
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QHeaderView>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
QTableWidget *tableWidget = new QTableWidget(this);
tableWidget->setColumnCount(3);
tableWidget->setHorizontalHeaderLabels(QStringList() << "Name" << "Age" << "City");
connect(tableWidget->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(sortTable(int)));
QStringList names = {"Alice", "Bob", "Charlie", "David", "Eva"};
QStringList ages = {"25", "30", "20", "35", "28"};
QStringList cities = {"New York", "London", "Paris", "Tokyo", "Sydney"};
for (int i = 0; i < 5; i++)
{
QTableWidgetItem *nameItem = new QTableWidgetItem(names[i]);
QTableWidgetItem *ageItem = new QTableWidgetItem(ages[i]);
QTableWidgetItem *cityItem = new QTableWidgetItem(cities[i]);
tableWidget->setItem(i, 0, nameItem);
tableWidget->setItem(i, 1, ageItem);
tableWidget->setItem(i, 2, cityItem);
}
setCentralWidget(tableWidget);
}
private slots:
void sortTable(int column)
{
tableWidget->sortByColumn(column);
}
private:
QTableWidget *tableWidget;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
```
阅读全文