Unsolved StyleSheet to change QLineEdit background while being edited
-
It is a concern in one of my projects that a user may edit text (entering a number, say), but then not leave the line edit, nor hit enter, and thus 'textEdited' is not emitted. I'd like to emphasize that the value on the screen does not match the value deeper in the software (that would be modified upon the 'textEdited' signal).
Currently, I'm changing the background color of the QLineEdit in each object separately. eg:
void MyWidget::on_lineEdit_1_textEdited(){ ui->lineEdit_1->setStyleSheet("background: pink"); } void MyWidget::on_lineEdit_1_editingFinished() { ui->lineEdit_1->setStyleSheet(""); backendThing->setValue1(ui->lineEdit_1->text()->toDouble()); }
But it's pretty onerous to have that code for each and every line edit box. What would be ideal is if QLineEdit had some state such that a style sheet could be
QLineEdit:whileEditing {background: pink}
My current stupid hack way will probably be to subclass QLineEdit, add in a dynamic property, then have stylesheet hook on that dynamic property? Is there a better solution out there?
-
followup: I've tried the following:
class MyLineEdit : public QLineEdit { Q_OBJECT public: MyLineEdit(QWidget* parent = 0); private slots: void onTextEdited(); void onEditingFinished(); }; MyLineEdit::MyLineEdit(QWidget* parent) : QLineEdit(parent) { setProperty("whileEditing", false); connect(this, &QLineEdit::textEdited, this, &MyLineEdit::onTextEdited); connect(this, &QLineEdit::editingFinished, this, &MyLineEdit::onEditingFinished); } void MyLineEdit::onTextEdited() { setProperty("whileEditing", true); qDebug() << "a" << property("whileEditing").toString(); } void MyLineEdit::onEditingFinished() { setProperty("whileEditing", false); qDebug() << "b" << property("whileEditing").toString(); }
and set the main window stylesheet to:
this->setStyleSheet("*[whileEditing=\"true\"]{background-color: pink}");
But no change in background.
I then changed 'whileEditing' to true at construction time, and it changed the background to pink but then did not change back after editing finished.
it seems that stylesheet will set background once and then not pay attention to dynamic property changes later.
So really, I think QLineEdit needs to have a state that you can query like "hover" or "focus" that indicates when its state is intermediate between 'textEdited()' and 'editingFinished()' -
Hi,
Something you can do when you change your property is to call.
style()->unpolish(this); style()->polish(this);
Hope it helps
-
@shavera Did you tried to call QWidget::Update() after modifing your whileEditing property ?