QT gridlayout 循环设置组件,表格也通用 已解决

时间:2024-03-23 16:51:30

在需求中。经常遇到,表格 展示需求。 几乎都是json格式的。 

// 列表配置文件
	QJsonArray listJsonArray = getCfgJsonData("details_tab_table_config.json");
	if (listJsonArray.isEmpty())
	{
		return;
	}

	ui->gridWidget->setMaximumSize(QSize(310, 180));
	ui->gridWidget->setMinimumSize(QSize(310, 180));
	int row = 0;
	int column = 0;

	for (int i = 0; i < listJsonArray.size(); ++i)
	{
		if (column == 1)
		{
			column = 0;
			row += 1;
		}

		column += 1;

		QJsonValue jsonValue = listJsonArray.at(i);
		bool bShow = jsonValue.toObject().value("is_show").toBool();
		QString name = jsonValue.toObject().value("name").toString();
		QString value = jsonValue.toObject().value("value").toString();

		QLabel* pName = new QLabel();
		pName->setText(name);
		pName->setAlignment(Qt::AlignCenter);
		pName->setMaximumWidth(100);
		pName->setMaximumHeight(38);
		pName->setStyleSheet("QLabel{ border-right: 1px solid #1C88E5; background-color:rgba(0, 51, 204, 0.3); color: #FFFFFF; font-size:14px; font-bold:10px;  }");

		QLabel* pValue = new QLabel();
		pValue->setText(name);
		pValue->setMaximumHeight(38);
		pValue->setAlignment(Qt::AlignVCenter);
		pValue->setStyleSheet("QLabel{ border:none; margin-left:5px; color: #FFFFFF; font-size:14px; font-bold:10px;  }");

		//中间用个空widget隔开
		QWidget* widget = new QWidget;
		if (i == 0)
		{
			widget->setStyleSheet("QWidget{border-top: 1px solid #1C88E5;border-left: 1px solid #1C88E5;border-right: 1px solid #1C88E5;}");
		}

		if (i > 0 && i < listJsonArray.size())
		{
			widget->setStyleSheet("QWidget{border: 1px solid #1C88E5;border-bottom:none;}");
		}

		if (i == listJsonArray.size())
		{
			widget->setStyleSheet("QWidget{border-bottom: 1px solid #1C88E5; border-left: 1px solid #1C88E5;border-right: 1px solid #1C88E5;}");
		}

		QHBoxLayout* layout = new QHBoxLayout(widget);
		layout->setContentsMargins(0, 0, 0, 0);
		layout->addWidget(pName);
		layout->addWidget(pValue);

		ui->gridLayout_2->addWidget(widget, row, column);
	}

函数


QJsonArray CCendDetailsTabWidget::getCfgJsonData(QString jsonStr)
{
	QJsonArray jsonArray;

	QString jsonPathStr = getConfigPath(jsonStr);
	QFile jsonFile(jsonPathStr);

	if (jsonFile.exists() && jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		jsonArray = QJsonDocument::fromJson(jsonFile.readAll()).array();
	}

	return jsonArray;
}

QString CCendDetailsTabWidget::getConfigPath(QString fileName)
{
	QString appDirPath = QCoreApplication::applicationDirPath();
	return appDirPath + "/config/" + fileName;
}