How can my stylesheet account for custom properties?

In order to account for custom properties in your stylesheet, you can use the Property Selector, see:

http://doc.qt.nokia.com/stylesheet-syntax.html#selector-types
http://doc.qt.nokia.com/stylesheet-examples.html#customizing-using-dynamic-properties

If the value of the Qt property changes after the style sheet has been set, you will probably have to force a style sheet recomputation. This can be done by calling

  1. style()->unpolish(theWidget);
  2. style()->polish(theWidget);
  3.  
  4.  

Alternatively, you can unset the style sheet and set it again, but this is more expensive than the first solution.

The following example demonstrates how this can be done:

  1. #include <QtGui>
  2.  
  3. class LineEdit : public QLineEdit
  4. {
  5.   Q_OBJECT
  6. public:
  7.   LineEdit(QWidget *wid) : QLineEdit(wid)
  8.   {
  9.     setProperty("theMaximum", false);
  10.     setStyleSheet("QLineEdit[theMaximum=\"true\"] {background-color: black}\
  11.            QLineEdit[theMaximum=\"false\"] {background-color: red}");
  12.     oldSheet = styleSheet();
  13.     QTimer::singleShot(3000, this, SLOT(test1()));
  14.   }
  15.   public slots:
  16.     void test1()
  17.     {
  18.       setProperty("theMaximum", true);
  19. #if 1
  20.       style()->unpolish(this);
  21.       style()->polish(this);
  22. #else
  23.       setStyleSheet(styleSheet());
  24. #endif
  25.     }
  26. private:
  27.   QString oldSheet;
  28. };
  29.  
  30. #include "main.moc"
  31.  
  32. int main(int argc, char** argv)
  33. {
  34.   QApplication app(argc, argv);
  35.   QWidget window;
  36.   QVBoxLayout *layout = new QVBoxLayout(&window);
  37.   layout->addWidget(new LineEdit(&window));
  38.   layout->addWidget(new QLabel("This is a LineEdit", &window));
  39.   window.show();
  40.   return app.exec();
  41.  
  42. }
  43.  

No comments

Write a comment

Sorry, you must be logged in to post a comment.