当前位置: 代码迷 >> QT开发 >> 一个从QWidget派生的简单类通过setStyleSheet设置背景无效的有关问题
  详细解决方案

一个从QWidget派生的简单类通过setStyleSheet设置背景无效的有关问题

热度:113   发布时间:2016-04-25 03:10:22.0
一个从QWidget派生的简单类通过setStyleSheet设置背景无效的问题
版本:QT4.8
我写了个简单的程序:创建QWidget对象,并设置到QDockWidget中,在主窗口停靠。
如果直接创建的QWidget创建的对话框,通过setStyleSheet设置背景颜色有效,
如果用自定义的QWidget派生类LeftMenuDlg来创建对话框,设置背景颜色无效.
非常疑惑,为什么如此简单的派生操作,会导致功能变化?还请大侠帮忙解惑。

int main(...)
{
...
QWidget *_leftMenuDlg;
dock = new QDockWidget("LeftMenuDlg", this);
dock->setAllowedAreas(Qt::LeftDockWidgetArea);
dock->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
_leftMenuDlg= new QWidget(dock); // 直接创建QWidget对象,执行结果窗口停靠正确,背景色设置成功
dock->setWidget(_leftMenuDlg);
dock->setStyleSheet("background: blue");
addDockWidget(Qt::LeftDockWidgetArea,dock);
....
}


程序中,对_leftMenuDlg= new QWidget(dock); 的 QWidget对象进行派生,声明自己的QWidget派生类LeftMenuDlg,后使用
_leftMenuDlg = new LeftMenuDlg(dock),创建派生对话框,结果,使用LeftMenuDlg创建的对话设置背景色无效

// LeftMenuDlg.h
class LeftMenuDlg : public QWidget//, Ui::dialog_Left
{
Q_OBJECT
public:
LeftMenuDlg(QWidget *parent = 0);
~LeftMenuDlg();

private slots:
void on_click_leftBtn1();
};

//LeftMenuDlg.cpp
LeftMenuDlg::LeftMenuDlg(QWidget *parent/* = 0*/)
:QWidget(parent)
{
}

LeftMenuDlg::~LeftMenuDlg()
{
}

void LeftMenuDlg::on_click_leftBtn1()
{
}



------解决思路----------------------
多看看Manual:

Qt Style Sheets Reference

引用
QWidget
Supports only the background, background-clip and background-origin properties.
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
 void CustomWidget::paintEvent(QPaintEvent *)
 {
     QStyleOption opt;
     opt.init(this);
     QPainter p(this);
     style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
 }
The above code is a no-operation if there is no stylesheet set.
Warning: Make sure you define the Q_OBJECT macro for your custom widget.