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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With