8

How can I load a style sheet (.qss style resource) globally with Qt?

I am trying to make things a bit more efficient than:

middleIntText -> setStyleSheet("QLineEdit {  border: 1px solid gray;
                                border-radius: 5px;padding: 0 8px;
                                selection-background-color:darkgray;
                                height:40px;font-size:15px;}");

I thought the following would work at loading QLineEdit the one time for all QLineEdit widgets:

qss file:

QLineEdit {     border: 1px solid gray;
                border-radius: 5px;
                padding: 0 8px;
                selection-background-color:darkgray;
                height:40px;
                font-size:15px;}

cpp file:

QApplication a(argc, argv);
QFile stylesheet("formStyle.qss");
stylesheet.open(QFile::ReadOnly);
QString setSheet = QLatin1String(stylesheet.readAll());
a.setStyleSheet(setSheet);

Perhaps this is right and I am doing something else wrong?

Brandon Clark
  • 788
  • 1
  • 13
  • 26
  • I have been talking to some guys over in the [Qt Forums](http://qt-project.org/forums/viewthread/19124/) and believe I may know what I need to do. Report back tomorrow with a solution. It can basically be the file location of .qss, css syntax or just picking the right object to cascade down (ie. QMainWindow::setStyleSheet(QString)). The method above should work once I figure which one of the three. – Brandon Clark Jul 27 '12 at 07:29

2 Answers2

7

You called QStyle * QApplication::setStyle ( const QString & style ) which requests a QStyle object for style from the QStyleFactory.

Instead, you should call void QApplication::setStyleSheet ( const QString & sheet ) which sets the application style sheet.

Bill
  • 11,595
  • 6
  • 44
  • 52
  • You are correct. Although this make no change, but I have changed the above code to reflect this part in the correct syntax. I posted a comment below my question regarding the assumed answers. I should have the actual answer tomorrow. – Brandon Clark Jul 27 '12 at 07:33
4

The above attempt is correct syntax but there are reasons it may not work.

Possible problems:

  1. Source file(.qss) is not being retrieved

  2. Incorrect top widget being chosen to apply cascade.

  3. Syntax of the .qss (CSS) code.

Reason I had to ask my question above is I had two of these three issues. I first had to point to the files correct location and second I had to apply directly to QWidget.

QFile stylesheet("G:/Applications/Projects/ProspectTracker/formStyle.qss");
stylesheet.open(QFile::ReadOnly);
QString setSheet = QLatin1String(stylesheet.readAll());
QWidget::setStyleSheet(setSheet);

@Bill Thank for your assistance. He pointed out that I had posted .setStyle and not .setStyleSheet. The sample code above no longer reflects this but if I didn't change that nothing I did would have worked.

Brandon Clark
  • 788
  • 1
  • 13
  • 26