PDA

View Full Version : Avoiding unwanted button signals.



Eos Pengwern
6th January 2010, 15:14
Hello,

I wrote the following code example when I was trying to troubleshoot a problem with an editable QComboBox. I solved the original problem, but along the way encountered another issue that has so far defeated me.

Essentially, the QPushButton in the dialog box seems to emit a 'clicked' signal whenever I press Enter, even if it is the QComboBox that has focus at the time. I discovered this because I was trying to find out why, whenever I edited the text in the QComboBox, an unwanted new item appeared under my newly-edited text. I eventually discovered that the unwanted new item wasn't being inserted by the QComboBox (at least, not so long as I explicitly set the InsertPolicy to QComboBox::InsertAtCurrent), but rather by the "addItem" slot being called in response to a perceived clicked() signal from the button.

So how can I force the QPushButton to ignore keypresses that are none of its business? Explicitly putting "setDefault(false)" has made no difference.

Here is the code:


#include <QtGui/QApplication>
#include <Qt/qglobal.h>

#include <QDialog>
#include <QLabel>
#include <QComboBox>
#include <QPushButton>
#include <QGridLayout>
#include <QVBoxLayout>

class ComboTest : public QWidget
{
Q_OBJECT

public:
ComboTest(QWidget *parent = 0)
: QWidget(parent)
{
Layout = new QGridLayout;
Label = new QLabel;
Combo = new QComboBox;
Combo -> setEditable(true);
Combo -> addItem("Original default");
Combo -> setInsertPolicy(QComboBox::InsertAtCurrent);
Button = new QPushButton("Add Item");
Button -> setDefault(false);
Label -> setText(Combo -> currentText());

Layout->addWidget(Label, 0, 2);
Layout->addWidget(Button, 2, 0);
Layout->addWidget(Combo, 2, 2);
setLayout(Layout);

connect(Button, SIGNAL(clicked(const bool &)),
this, SLOT(addItem(const bool &)));
connect(Combo, SIGNAL(editTextChanged(const QString &)),
this, SLOT(synchroniseText(const QString &)));
connect(Combo, SIGNAL(currentIndexChanged(int)),
this, SLOT(showSelection(int)));
}

public slots:
void addItem(const bool &checked)
{
Combo -> addItem("New default");
}

void synchroniseText(const QString &newText)
{
Label -> setText(newText);
}

void showSelection(int newSelection)
{
Label -> setText(Combo -> itemText(newSelection));
}

private:
QGridLayout *Layout;
QLabel *Label;
QComboBox *Combo;
QPushButton *Button;
};

#include "main.moc"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDialog dialog;
QVBoxLayout* layout = new QVBoxLayout(&dialog);
layout->addWidget(new ComboTest);
dialog.setLayout(layout);
return dialog.exec();
}

Many thanks,
Stephen.

numbat
7th January 2010, 12:16
Try adding:


Button -> setAutoDefault(false);

Eos Pengwern
7th January 2010, 15:58
Try adding:


Button -> setAutoDefault(false);


Yes indeed, that fixes it.

Excellent!