QLineEdit set color based on valid input?
-
Good day all, hope your day is going well. Got a question and any advice would be appreciated. I have a QLineEdit that accepts a 2 digit ID number. I have it currently set to display a red background color if there's no ID and a green color whenever I type in 2 digits. Problem is at the start of the application, the QLineEdit box is white. Can I somehow set the textEdited() signal on start to true so that it triggers my checkID() method?
On app start, it should be red background as there's no valid input.
mainwindow.h
void checkID(const QString &id);
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->IDLineEdit, &QLineEdit::textEdited, this, &MainWindow::checkID); ui->IDLineEdit->setValidator(new QRegularExpressionValidator(QRegularExpression("^[1-9]{2}$"), this)); } void MainWindow::checkID(const QString &id) { bool empty = ui->IDLineEdit->hasAcceptableInput(); ui->IDLineEdit->setStyleSheet(empty ? "background-color: green" : "background-color: red"); }
-
@Calicoder said in QLineEdit set color based on valid input?:
. Can I somehow set the textEdited() signal on start to true so that it triggers my checkID() method?
No, but your slot method
checkID()
can be called explicitly, e.g. at the end of yourMainWindow
constructor. Slot methods are like any method, you can just call them directly as well as via a signal.