以下是一个示例代码,演示了如何使用Qt中的QTableWidget创建可选表格,并将其保存到文件中:
#include <QApplication>
#include <QTableWidget>
#include <QFileDialog>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTableWidget table(2, 3); // 创建一个2行3列的表格
table.setSelectionBehavior(QAbstractItemView::SelectRows); // 设置为整行选择
table.setHorizontalHeaderLabels({"Name", "Age", "Gender"}); // 设置表头标签
// 添加数据
QTableWidgetItem* item1 = new QTableWidgetItem("John");
QTableWidgetItem* item2 = new QTableWidgetItem("28");
QTableWidgetItem* item3 = new QTableWidgetItem("Male");
table.setItem(0, 0, item1);
table.setItem(0, 1, item2);
table.setItem(0, 2, item3);
QTableWidgetItem* item4 = new QTableWidgetItem("Mary");
QTableWidgetItem* item5 = new QTableWidgetItem("32");
QTableWidgetItem* item6 = new QTableWidgetItem("Female");
table.setItem(1, 0, item4);
table.setItem(1, 1, item5);
table.setItem(1, 2, item6);
QString filename = QFileDialog::getSaveFileName(nullptr, "Save File", "", "CSV files (*.csv)"); // 弹出文件保存对话框
QFile file(filename); // 创建文件对象
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { // 打开文件
QTextStream out(&file); // 创建文本流对象
// 遍历表格中所有行
for (int row = 0; row < table.rowCount(); ++row) {
// 遍历当前行中所有列
for (int col = 0; col < table.columnCount(); ++col) {
QString data = table.item(row, col)->data(Qt::DisplayRole).toString(); // 获取单元格数据
out << data; // 写入文件
if (col != table.columnCount() - 1) { // 如果不是最后一列,加上分隔符
out << ",";
}
}
out << "\n"; // 换行
}
file.close();
}
return app.exec();
}
在这个示例中,我们首先创建了一个2行3列的表格,并设置为整行选择模式。然后,我们添加了一些数据,并使用QFileDialog弹出文件保存对话框,让用户选择要保存的文件名和路径。接下来,我们创建了一个QFile对象,并打开该文件以进行写入。然后,我们使用QTextStream创建文本流对象,并遍历了表格中的所有行和列,将每个单元格的数据以逗号分隔的形式写入到文件中,并换行分隔每行数据。最后,我们关闭了文件并返回了主应用程序的控制权。
请注意,这只是一个简单的示例代码,您可以根据自己的需求修改它。