去年开始做界面,不过在过去的一年用的MFC,从今年开始用Qt.确实用Qt来做界面比MFC简单,而且更容易做出来炫炫的效果。折腾的这段时间里,其实每天都会发现新的问题,只是太懒了,一直都没记录下来。今天就来个开始吧:
问题描述:
我有两个QComboBox combo1, combo2:
QComboBox *combo1 = new QComboBox;
QComboBox *combo2 = new QComboBox;
combo1->addItem("1-1");
combo1->addItem("1-2");
combo2->addItem("2-1");
combo2->addItem("2-2");
connect(combo1, SIGNAL(currentIndexChanged(int)), combo2, SLOT(process(int)));
connect(combo2, SIGNAL(currentIndexChanged(int)), combo1, SLOT(process(int)));
然后是信号处理函数:
void process(int index)
{
QComboBox *combo1 = new QComboBox;
QComboBox *combo2 = new QComboBox;
if (sender() == combo1)
{
combo2->setCurrentIndex(index);
}
else if (sender() == combo2)
{
combo1->setCurrentIndex(index);
}
}
这样两个combobox之间就产生了死循环。因为不管是手动改变combobox的当前index还是使用函数来设置当前的index都会发出index改变的消息,此时就需要使用关闭信号:
void process(int index)
{
QComboBox *combo1 = new QComboBox;
QComboBox *combo2 = new QComboBox;
if (sender() == combo1)
{
combo2->blockSignals(true);
combo2->setCurrentIndex(index);
combo2->blockSignals(false);
}
else if (sender() == combo2)
{
combo1->blockSignals(true);
combo1->setCurrentIndex(index);
combo1->blockSignals(false);
}
}
好了,就这么多,写个文章还真不容易啊!