PDA

View Full Version : How to use stylesheet of custom widget



luochen601
20th September 2010, 10:43
Hi all,

I made my custom widget based on QWidget.

I use stylesheet like this:

customWidget->setStyleSheet("QWidget { border: none; background-color: rgb(195, 198, 201);} QWidget:hover {background-color: rgb(255, 0, 0);"}

But it has no effect, so why and how to perform?

Lykurg
20th September 2010, 13:46
Maybe you want to replace QWidget with the class name of your subclassed widget.

luochen601
21st September 2010, 03:54
Maybe you want to replace QWidget with the class name of your subclassed widget.

I tried to use the class name of my subclass, Unfortunately, It is no effect either. But thanks for your heartful.

Lykurg
21st September 2010, 06:32
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0): QWidget(parent)
{}
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QString css = "background-color: #ffA500; border: 5px solid #FF0000;";

MyWidget b;
b.setAutoFillBackground(true);
b.setStyleSheet(css);
b.show();

return app.exec();
} Works for me. If you have your own paint event use something like
void paintEvent(QPaintEvent *e)
{
QWidget::paintEvent(e); // draws the background etc.
//or use
QStylePainter p(this);
//to draw your needed elements.
}

luochen601
21st September 2010, 08:29
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0): QWidget(parent)
{}
};


OK, your code works fine in my system too.
But if you add the Q_OBJECT in subclass define, no effect either.
Qt Code:

class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = 0): QWidget(parent) {}
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QString css = "background-color: #ffA500; border: 5px solid #FF0000;";

MyWidget b;
b.setAutoFillBackground(true);
b.setStyleSheet(css);
b.show();

return app.exec();
}

Lykurg
21st September 2010, 09:43
#include <QtGui>

class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = 0): QWidget(parent) {}
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QString css = "background-color: #ffA500;";

MyWidget b;
b.setAutoFillBackground(true);
b.setStyleSheet(css);
b.show();

return app.exec();
}

#include "main.moc"does draw a orange background on my machine. Have you rerun qmake?

luochen601
21st September 2010, 09:54
does draw a orange background on my machine. Have you rerun qmake?

My machine still no effect if add Q_OBJECT.
Sorry, what did you mean of "rerun qmake"? I am a beginner, just install the Qt Creator and write code. How to rerun qmake? Thanks a lot.

Lykurg
21st September 2010, 10:10
I don't know how it is called on the english ui, but have a look at the menu bar "compilation" or something like that. Call "clean all" and "run qmake" and "compile". Or on the qt command promt type (in the project/build directory)

make clean
del Makefile*
qmake
make