PDA

View Full Version : segmentation fault with QLineEdit Sender



saman_artorious
15th January 2014, 16:11
I have a few QLineEdit-s; When the Edit QPushButton is clicked, I want to know which QLineEdit was selected beforehand.


QLineEdit *clickedLine = qobject_cast<QLineEdit *>(sender());
clickedLine->setText(";)");


However, in the case I have several push button and want to know which button was clicked, this is accomplished successfully with the same code snippet:



QPushButton *clickedButton = qobject_cast<QPushButton *>(sender());
int digitValue = clickedButton->text().toInt();
qDebug() << digitValue;

anda_skoa
15th January 2014, 20:35
Check if sender() returns a QLineEdit pointer. a simple qDebug() << sender() should to.

Cheers,
_

ChrisW67
16th January 2014, 00:31
If clickedLine == 0, as it will when the sender is not a QLineEdit, then your code crashes. Hardly a surprise there.

What saman_artorious seems to want though is to know which of many QLineEdits had the focus before the user clicked the button so that the slot can read that line edit and not the others. Of course, none of the line edits might have focus when the button is pressed or an unrelated line edit/widget might have focus etc. I don't know that it is generally possible to do this based on the current focussed widget (i.e. QApplication::focusWidget()). Even setting the push button to NoFocus and clicking with a line edit active may result in another widget having the focus by the time the clicked() slot processes. Seems you would have to track the last used QLineEdit using the editingFinished() or similar signal (or subclass and use the focusInEvent()).

Seems like a terrible UI design to me but then it is not my project.

stampede
16th January 2014, 06:49
In case each lineedit has its own "Edit" button, you can wrap the line edit and push button into one class and pass through the clicked() signal of QPushButton:


class Wrapper : public QWidget{
Q_OBJECT
public:
Wrapper(QWidget * parent = NULL) : QWidget(parent)
{
// initialize button and line edit, prepare layout etc...
connect(_button, SIGNAL(clicked()), this, SIGNAL(buttonClicked()));
}
QLineEdit * lineEdit() const{
return _lineEdit;
}
signals:
void buttonClicked();

private:
QLineEdit * _lineEdit;
QPushButton * _button;
};


//...

void Class::onClickedSignal(){
Wrapper * wrap = qobject_cast<Wrapper*>(sender());
if (wrap){
QLineEdit * lineEdit = wrap->lineEdit();
//...
}
}



Another way is to connect to QLineEdit::editingFinished() signal instead.