对于基于QObject的控件都有这个属性,例如QPushButton、QNetworkReply对象等。如下,可以根据VS的提示看下控件是否有这个方法。
setproperty+property属性可以使控件携带特定信息,用作标识,十分方便好用。
设置标识的方法原型:
bool QObject::setProperty(const char *name, const QVariant &value);
取标识的方法原型:
QVariant QObject::property(const char *name) const
这里参数name为自定义的标识名称;value为此标识对应的值。
这里记录new出的第几个button,当点击button时,可以获取该button的序号。
QPushButton* m_button = new QPushButton();
//绑定序号信息,id就是属性名字,i就是值
m_button->setProperty("id", i);
//同一个控件也可以绑定多个信息,继续绑定,这里的值也可以是字符串
m_button->setProperty("name", "value");
//槽函数,传递信息
connect(m_button, &QPushButton::clicked, this, [=]
{
int index = m_button->property("id").toInt();
QString message= m_button->property("name").toString();//message="value"
……
});