前言
最近了解了一下setProperty和property,突然萌生一个想法,之前写的代码有很大优化空间,就是控件可以绑定值了,我这里拿QTableWidget每一行绑定一个结构体写个demo演示一下,dddd!
一、绑定
结构体如下:
struct ST_Test
{
char szName[256];
int iLen;
char c;
char szPhone[32];
ST_Test(){}
ST_Test(char* pName, int len, char cc, char* pPhone)
{
strcpy(szName, pName);
iLen = len;
c = cc;
strcpy(szPhone, pPhone);
}
};
构造函数申明结构体链表:
m_listTest.append(new ST_Test{"Test001", 911, 8, "1234556789"});
m_listTest.append(new ST_Test{"Test002", 285, 9, "1234556780"});
m_listTest.append(new ST_Test{"Test003", 111, 10, "1234556781"});
保存结构体指针:
Q_DECLARE_METATYPE(ST_Test*)
QCheckBox* cBox = nullptr;
int iRow = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(iRow);
cBox = new QCheckBox("1");
ui->tableWidget->setCellWidget(iRow, 0, cBox);
ui->tableWidget->setItem(iRow, 1, new QTableWidgetItem("测试1"));
ui->tableWidget->setItem(iRow, 2, new QTableWidgetItem("Ok 1"));
cBox->setProperty("ST_Test", QVariant::fromValue(m_listTest[0]));
iRow = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(iRow);
cBox = new QCheckBox("2");
ui->tableWidget->setCellWidget(iRow, 0, cBox);
ui->tableWidget->setItem(iRow, 1, new QTableWidgetItem("测试2"));
ui->tableWidget->setItem(iRow, 2, new QTableWidgetItem("Ok 2"));
cBox->setProperty("ST_Test", QVariant::fromValue(m_listTest[1]));
iRow = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(iRow);
cBox = new QCheckBox("3");
ui->tableWidget->setCellWidget(iRow, 0, cBox);
ui->tableWidget->setItem(iRow, 1, new QTableWidgetItem("测试3"));
ui->tableWidget->setItem(iRow, 2, new QTableWidgetItem("Ok 3"));
cBox->setProperty("ST_Test", QVariant::fromValue(m_listTest[2]));
二、获取
代码如下(示例):
QCheckBox* cBox = qobject_cast<QCheckBox*>(ui->tableWidget->cellWidget(0, 0));
if(cBox != nullptr)
{
QVariant curData = cBox->property("ST_Test");
if(curData.isNull())
{
return;
}
ST_Test* pTest = curData.value<ST_Test*>();
qDebug() << cBox->text() << " " << pTest->szName << " " << pTest->iLen << " " << pTest->c << " " << pTest->szPhone;
}
cBox = qobject_cast<QCheckBox*>(ui->tableWidget->cellWidget(1, 0));
if(cBox != nullptr)
{
QVariant curData = cBox->property("ST_Test");
if(curData.isNull())
{
return;
}
ST_Test* pTest = curData.value<ST_Test*>();
qDebug() << cBox->text() << " " << pTest->szName << " " << pTest->iLen << " " << pTest->c << " " << pTest->szPhone;
}
cBox = qobject_cast<QCheckBox*>(ui->tableWidget->cellWidget(2, 0));
if(cBox != nullptr)
{
QVariant curData = cBox->property("ST_Test");
if(curData.isNull())
{
return;
}
ST_Test* pTest = curData.value<ST_Test*>();
qDebug() << cBox->text() << " " << pTest->szName << " " << pTest->iLen << " " << pTest->c << " " << pTest->szPhone;
}
|