天天看點

重置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();
}
           

運作結果:

重置QComboBox項的時候産生currentIndexChanged信号

     點選了按鈕之後:           

重置QComboBox項的時候産生currentIndexChanged信号

應用程式輸出:

"current index changed..."

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

"current index changed..."

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

其他情況:

1.如果QComboBox裡添加項,則不産生currentIndexChanged信号。

2.删除QComboBox某一項,若目前項在該項之前,則不産生信号;若目前項要删除或目前項在删除項之後,則會産生一次信号。

繼續閱讀