Solved QlineEdit in focus
-
Hi,
I would like to change the background color of QLineEdit when it is in focus. Can somebody please show me which is the best way of doing it?Thank you.
-
You can use setStyleSheet(const QString & styleSheet), for a style sheet description see: http://doc.qt.io/qt-5/stylesheet.html
-
@gabor53
You may also tryQPalette palette; palette.setColor(QPalette::Base,Qt::black); palette.setColor(QPalette::Text,Qt::white); ui->lineEdit->setPalette(palette);
-
How can I know that lineEdit is in focus?
Thnks. -
Hi,
Either connect the QApplication signal focusChanged() to your slot:
http://doc.qt.io/qt-5/qapplication.html#focusChangedOr reimplement the focusInEvent() method in a custom MyLineEdit, that inherits from QLineEdit, and promote your QLineEdit in QtDesigner using MyLineEdit.
http://doc.qt.io/qt-5/qwidget.html#focusInEventOr you can use style sheet as @jsulm suggested:
setStyleSheet("QLineEdit:focus {...}");If you want only one QLineEdit to have a specific behavior, then give it a name with setObjectName() or through QtDesigner, and use it in the style sheet string:
setStyleSheet("QLineEdit:focus#myLineEdit {...}");But I realize that I'm giving you different options without telling you what's the best one. I'd say style sheet, but only because it seems easier. I don't really know the mechanisms behind every solution.
-
Thank you, it worked with LineEdit. Should this work with QComboBox too? I tried
setStyleSheet("QComboBox:focus#comboBox{background-color: rgb(170, 255, 127)}");
but nothing happened.
Thank you for all your help. -
Each time I need to apply a style sheet, I read the documentation first.
Here is the list of pseudo states:
http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-pseudo-states
And it is said::focus The item has input focus.
I don't really know what "input focus" means for QCombBox, maybe it's when it's editable and its line edit has the focus. So then I'd go see how they style a QComboBox in examples:
http://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcomboboxI recommend you to read carefully these topics:
http://doc.qt.io/qt-5/stylesheet.html
http://doc.qt.io/qt-5/stylesheet-syntax.html
http://doc.qt.io/qt-5/stylesheet-designer.html (optional)
http://doc.qt.io/qt-5/stylesheet-customizing.html
http://doc.qt.io/qt-5/stylesheet-reference.html
http://doc.qt.io/qt-5/stylesheet-examples.htmlAfter reading them, you'll have a global sight of what are style sheets in Qt, how to use them properly, and what can be done and can't.
-
Thank you.