qt6 c++操作qtableview和yaml

  • 保存qtableview数据到yaml文件
  • 从yaml文件读取数据到qtableview

qtableview在UI界面拖放。
代码是问chat百度的深度探索。

- name: a1
  address: db1.dbw10
  type: int
- name: a2
  address: db1.dbx1.0
  type: 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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

容沁风

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

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

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

打赏作者

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

抵扣说明:

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

余额充值