重置QComboBox項的時候產生currentIndexChanged信號

問題描述:
程序中經常使用下拉框控件QComboBox,我們知道在Qt中每當用戶重新選擇了一個項的時候QComboBox會產生currentIndexChanged信號。在有必要的情況下,在程序中需要清空QComboBox並重置項,這時候同樣會產生這個信號,並且會產生2次。一次在清空的各項的時候,一次在重置各項的時候。

 

 

例子:
TestDialog.h文件:

#ifndef TESTDIALOG_H
#define TESTDIALOG_H

#include <QObject>
#include <QDialog>
#include <QPushButton>
#include <QComboBox>


class TestDialog : public QDialog
{
    Q_OBJECT

public:
    TestDialog(QWidget *parent = 0);

public slots:
    void comboBoxValueChanged();
    void changeComboBoxValue();

private:
    QPushButton *button;
    QComboBox *comboBox;
};

#endif // TESTDIALOG_H

TestDialog.cpp文件:

#include "TestDialog.h"
#include <QtGui>

TestDialog::TestDialog(QWidget *parent) : QDialog(parent)
{
    setWindowTitle(tr("一個簡單的例子"));
    comboBox = new QComboBox;
    comboBox->addItems(QStringList()<<tr("牀前明月光")<<tr("疑是地上霜")
                       <<tr("舉頭望明月")<<tr("低頭思故鄉"));
    button = new QPushButton(tr("改變下拉框內容"));
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addStretch();
    layout->addWidget(button);
    QVBoxLayout *mainlayout = new QVBoxLayout;
    mainlayout->addWidget(comboBox);
    mainlayout->addLayout(layout);
    this->setLayout(mainlayout);

    connect(button, SIGNAL(released()), this, SLOT(changeComboBoxValue()));
    connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxValueChanged()));
}

void TestDialog::changeComboBoxValue()
{
    comboBox->clear();
    qDebug()<<"======1======";
    comboBox->addItems(QStringList()<<tr("竹外桃花三兩枝")<<tr("春江水暖鴨先知")
                       <<tr("蔞蒿滿地蘆芽短")<<tr("正是河豚欲上時"));
    qDebug()<<"======2======";
    return ;
}

void TestDialog::comboBoxValueChanged()
{
    qDebug()<<tr("current index changed...");
}

main.cpp文件:

#include <QtGui/QApplication>
#include <QTextCodec>
#include "TestDialog.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    /*設置編碼格式*/
    QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));

    TestDialog *dialog = new TestDialog;
    dialog->show();

    return app.exec();
}


運行結果:

     點擊了按鈕之後:           

應用程序輸出:
"current index changed..."

======1======

"current index changed..."

======2======

 

其他情況:
1.如果QComboBox裏添加項,則不產生currentIndexChanged信號。
2.刪除QComboBox某一項,若當前項在該項之前,則不產生信號;若當前項要刪除或當前項在刪除項之後,則會產生一次信號。

 

 

發佈了42 篇原創文章 · 獲贊 30 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章