qt6 c++操作qtableview和yaml
- 保存qtableview数据到yaml文件
- 从yaml文件读取数据到qtableview
qtableview在UI界面拖放。
代码是问chat百度的深度探索。
- name: a1address: db1.dbw10type: int
- name: a2address: db1.dbx1.0type: bool
写到yaml,写前检查
bool plot1::isRowValid(const QStandardItemModel* model, int row) {std::array<int, 3> cols = { 0,1,2 };return std::all_of(cols.begin(), cols.end(), [&](int col) {QStandardItem* item = model->item(row, col);return item && !item->text().isEmpty();});
}
用的库是yaml-cpp 0.8,需要cmake编译。
void plot1::saveToYaml() {YAML::Emitter emitter;emitter << YAML::BeginSeq;for (int row = 0; row < g_model->rowCount(); ++row) {if (!isRowValid(g_model, row)) continue;emitter << YAML::BeginMap<< YAML::Key << "name" << YAML::Value << g_model->item(row, 0)->text().toStdString()<< YAML::Key << "address" << YAML::Value << g_model->item(row, 1)->text().toStdString()<< YAML::Key << "type" << YAML::Value << g_model->item(row, 2)->text().toStdString()<< YAML::EndMap;}emitter << YAML::EndSeq;std::ofstream fout("data.yaml");fout << emitter.c_str();
}
读取yaml
//检查项目行不为空 2
bool plot1::isItemValid(YAML::const_iterator it) {std::array<std::string, 3> cols = { "name","address","type" };return std::all_of(cols.begin(), cols.end(), [=](std::string col) {std::string s = (*it)[col].as<std::string>();return s.length() > 0;});
}//读取yaml到表
void plot1::loadYaml()
{try {YAML::Node config = YAML::LoadFile("data.yaml");g_model->removeRows(0, g_model->rowCount());for (YAML::const_iterator it = config.begin(); it != config.end(); ++it) {if (!isItemValid(it)) continue;QList<QStandardItem*> items;items << new QStandardItem(QString::fromStdString((*it)["name"].as<std::string>()));items << new QStandardItem(QString::fromStdString((*it)["address"].as<std::string>()));items << new QStandardItem(QString::fromStdString((*it)["type"].as<std::string>()));g_model->appendRow(items);}}catch (YAML::Exception& e) {qDebug() << "YAML Error:" << e.what();}
}