Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't QLineEdit Style change when focused?

I'm developing a GUI using Qt and its stylesheets. On the main window stylesheet I've put the following style:

QLineEdit:focus {
    border: 2px solid #006080;
}

But when I use it the style doesn't really change as I expected. However, if I put the same stylesheet directly on the desired component, it works like magic! But well, it's not really a good idea to put stylesheets on every single LineEdit I may want (which would greatly increase the amount of work needed to add new components or change the stylesheet), neither reapplying the stylesheet by adding code lines such as setStyleSheet(styleSheet()).

Does anyone know how to solve this?

like image 449
Luiz Rodrigo Avatar asked Jul 13 '11 19:07

Luiz Rodrigo


2 Answers

Odd, it works as desired on my copy of Qt using QLineEdit:focus using

QLineEdit:focus
{
    border: 2px solid #006080;
}

Are you sure you do not have a child style somewhere farther down the line overruling this? As it is on the MainWindow it will be the first thing to be overruled.

A potential work-around is to use an event filter:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->lineEdit->installEventFilter( this );
    ui->lineEdit_2->installEventFilter( this );
}

...

bool MainWindow::eventFilter( QObject *object, QEvent *event )
{
    QLineEdit* edit = qobject_cast< QLineEdit* >( object );

    if( edit != NULL )
    {
        if( event->type( ) == QEvent::FocusIn )
        {
            edit->setStyleSheet( QString( "border: 10px solid #000000;" ) );
        }
        else if( event->type( ) == QEvent::FocusOut )
        {
            edit->setStyleSheet( QString( "border: 1px solid #000000;" ) );
        }
    }
}

Of course QStyleSheets are simply QStrings so you can have pre-defined styles stored away for use.

like image 168
ssell Avatar answered Oct 03 '22 15:10

ssell


You can set focus styles programmatically if needed like this:

QString styleSheet = "QLineEdit { border: 1px solid; border-color:#dcdcdc; border-radius: 4px;} QLineEdit:focus{border:1px solid gray;}";

yourFancyEdit->setStyleSheet(styleSheet);
like image 34
Rammgarot Avatar answered Oct 03 '22 14:10

Rammgarot