最近項目中開發在用到QCombox,然而在開發中,踩到了一個坑,花了一個晚上,一直在想,好在最後找到問題所在了。
這是業務的流程。直接說重點:QCombox在下拉窗更新資料的時候,會預設把下拉窗的第一個條資料,設定為選中的狀态,這樣的話,就會産生curentTextChanged的一個信号,直接把邏輯層原先有的資料給修改了。
為此,進行了日志列印一探究竟:
void TalkWindow::getMicList(const QStringList & texts)
{
DEBUG_TRACE("getCurrentText %s" , m_pDeviceWidget->m_pMicrophoneCombox->currentText().toStdString().c_str());
if (m_pDeviceWidget == NULL) return;
m_pDeviceWidget->m_pMicrophoneCombox->clear();
int a = m_pDeviceWidget->m_pMicrophoneCombox->count();
m_pDeviceWidget->m_pMicrophoneCombox->setCurrentIndex(-1);
DEBUG_TRACE("getCurrentText1 %s", m_pDeviceWidget->m_pMicrophoneCombox->currentText().toStdString().c_str());
m_pDeviceWidget->m_pMicrophoneCombox->addItems(texts);
DEBUG_TRACE("getCurrentText2 %s", m_pDeviceWidget->m_pMicrophoneCombox->currentText().toStdString().c_str());
m_pDeviceWidget->m_pMicrophoneCombox->setCurrentIndex(-1);
m_pDeviceWidget->m_pMicrophoneCombox->insertItem(texts.size()+1, TR_TALK_DEVICE_COMBOX, 0);
m_pDeviceWidget->m_pMicrophoneCombox->setCurrentIndex(-1);
DEBUG_TRACE("getCurrentText3 %s", m_pDeviceWidget->m_pMicrophoneCombox->currentText().toStdString().c_str());
m_pDeviceWidget->m_pMicrophoneCombox->setCurrentIndex(-1);
DEBUG_TRACE("getCurrentText4 %s", m_pDeviceWidget->m_pMicrophoneCombox->currentText().toStdString().c_str());
m_pDeviceWidget->m_pMicrophoneCombox->setCurrentIndex(-1);
DEBUG_TRACE("getCurrentText!!!!! %s", m_pDeviceWidget->m_pMicrophoneCombox->currentText().toStdString().c_str());
}
日志顯如下:
Line 151: [D:TalkWindow+13100:10356] 23:05:55.942 101261.059234 getCurrentText 麥克風 (7.1 SOUND EFFECT GAMING HEADSET)
Line 152: [D:TalkWindow+13100:10356] 23:05:55.943 101261.059569 getCurrentText1
Line 155: [D:TalkWindow+13100:10356] 23:05:55.943 101261.060339 getCurrentText2 麥克風 (High Definition Audio 裝置)
Line 156: [D:TalkWindow+13100:10356] 23:05:55.944 101261.060662 getCurrentText3
Line 157: [D:TalkWindow+13100:10356] 23:05:55.944 101261.060866 getCurrentText4
Line 158: [D:TalkWindow+13100:10356] 23:05:55.944 101261.061036 getCurrentText!!!!!
在getCurrentText2的日志中,很明顯,把additems的資料加載完完,預設選中就變了,然後再執行 setCurrentIndex的時候,把預設選中置為空,也就是說,一共産生了兩次 textchange的信号。
解決辦法:
我目前的解決辦法是,在擷取資料的時候,先斷開信号槽的連接配接,disconnect函數,然後等把下拉窗的資料加載完,再connect函數連接配接上,這樣,加載資料就避免了發送兩次信号,修改原有的資料。當然也
可以一個标記bool值,信号發出去的時候,不去處理就好了,但是這樣的話,可能不太好控制。是以我選擇了前者。有更好的辦法,多多指教。