QLineEdit change text weight on activation

1.7k views Asked by At

I want to make QLineEdit looks like QLabel with bold text if it's inactive and like QLineEdit with normal weight if active. In my understanding "active" = when text cursor shown and user can enter a text.

I tried to apply this css:

QLineEdit {
    font-weight: normal;
    border: 1px solid black;
}

QLineEdit:!focus {
    font-weight: bold;
    border: none;
}

Border works as expected, but font-weight is always bold. I was thinking of creating my class to handle activation event, but can't found anything related with it.

I will be very thankful if somebody can help me.

2

There are 2 answers

2
Darkproduct On

You need to get your custom slot for the focusChanged event. There you can change the font like this:

QFont font = ui->lineEdit_search->font();
font.setWeight(QFont::Bold); // or
font.setWeight(QFont::Normal);
ui->lineEdit_search->setFont(font);

An example where I handled a LineEdit search box is here, but you have to customize it with the bold text.

void MainWindow::focusChanged(QWidget* old, QWidget* now)
{
    if(now != NULL &&
       now->objectName() == "lineEdit_search")
    {
        if(ui->lineEdit_search->text() == tr("Search..."))
        {
            ui->lineEdit_search->clear();

            QPalette *palette = new QPalette();
            palette->setColor(QPalette::Text,Qt::black);
            ui->lineEdit_search->setPalette(*palette);

            delete palette;
        }
    }
    else if(old != NULL &&
            old->objectName() == "lineEdit_search")
    {
        if(ui->lineEdit_search->text().isEmpty())
        {
            ui->lineEdit_search->setText(tr("Search..."));

            QPalette *palette = new QPalette();
            palette->setColor(QPalette::Text,Qt::gray);
            ui->lineEdit_search->setPalette(*palette);

            delete palette;
        }
    }
}
0
Pavan Chandaka On

When you turn your line edit to inactive,

//Set your line edit to read only
yourLineEdit->setReadOnly(true);

//Get your widget background color
const QColor clr = this->palette().color(QWidget::backgroundRole());

//Set the widget background color to both the line edit background and its border
QString backGroundstyle = "background-color: rgb(%1, %2, %3);";
QString borderStyle = "border: 1px solid rgb(%1, %2, %3);";

yourLineEdit->setStyleSheet(backGroundstyle.arg(clr.red()).arg(clr.green()).arg(clr.blue()) + borderStyle.arg(clr.red()).arg(clr.green()).arg(clr.blue()));

When you turn line edit to active

//Make your line edit read-write
yourLineEdit->setReadOnly(false);

//Bring back your styles.
QString backGroundstyle_active = "background-color: white;";
QString borderStyle_active = "border: 1px solid black;";

yourLineEdit->setStyleSheet(backGroundstyle_active + borderStyle_active);