我有一个函数接收我创建的类的QList。让我们称这个假设的课程为#34; Stuff"。所以,这个函数接收一个Stuff的QList
我遍历QList,并取决于" Stuff"的属性。对象,我将生成以下内容之一:
1)QLineEdit
2)QCheckBox
3)QComboBox
这不是实际代码,但这正是我基本上所做的:
void MyProgram::update(QList<Stuff> myStuffs)
{
this->mSignalMapper = new QSignalMapper();
foreach (Stuff stuff, myStuffs)
{
if (stuff.isInt())
{
QLineEdit* input = new QLineEdit();
//There is code here to setup the QLineEdit and fill an initial value
verticalLayout->addWidget(input); //verticalLayout is QVBoxLayout
QObject::connect(input, SIGNAL(editingFinished()), this->mSignalMapper, SLOT(map()));
this->mSignalMapper->setMapping(input, stuff.getMappingId());
/*
* NOTE: the stuff.getMappingId() function returns an int that is unique
* to that stuff object. I'm 100% sure each stuff object is getting
* a unique mapping ID */
QObject::connect(this->mSignalMapper, SIGNAL(mapped(int)), this, SLOT(onStuffChanged(int)));
}
else if (stuff.isBool())
{
QCheckBox* input = new QCheckBox();
//There is code here to setup the QCheckBox and set an initial value
verticalLayout->addWidget(input);
QObject::connect(input, SIGNAL(stateChanged(int)), this->mSignalMapper, SLOT(map()));
this->mSignalMapper->setMapping(input, stuff.getMappingId());
QObject::connect(this->mSignalMapper, SIGNAL(mapped(int)), this, SLOT(onStuffChanged(int)));
}
else if (stuff.isStringList())
{
QComboBox* input = new QComboBox();
//There is code here to setup the QComboBox and fill in values for the combo box
verticalLayout->addWidget(input);
QObject::connect(input, SIGNAL(activated(int)), this->mSignalMapper, SLOT(map()));
this->mSignalMapper->setMapping(input, stuff.getMappingId());
QObject::connect(this->mSignalMapper, SIGNAL(mapped(int)), this, SLOT(onStuffChanged(int)));
}
}
}
问题在于,如果我只触发其中一个Widget信号,通过编辑QLineEdit,或选中复选框,或更改组合框值,onStuffChanged(int)函数被称为N时间,其中N = mSignalMapper的映射数。
这里发生了什么?如果我遍历并创建10个小部件,则单击10个小部件中的1个小部件将调用该函数10次,并且这10次中的每次都传递与仅与我交互的1个对象关联的唯一int。因此,如果10个小部件中的第1个是具有唯一int ID 27的复选框,则onStuffChanged(int)函数将被调用10次,每次参数为27。
答案 0 :(得分:2)
问题在于这一行:
QObject::connect(this->mSignalMapper, SIGNAL(mapped(int)), this, SLOT(onStuffChanged(int)));
您正在进行相同的连接 N 次( N =您的&#34;东西&#34;计数),因此每个mapped()
信号触发onStuffChanged(int)
广告位 N 次也。
<强>解决方案:强> 将此行移到循环外部,仅调用一次。