阿呆游乐园 https://bbs.21ic.com/?645097 [收藏] [复制] [RSS] 所谓的技术只不过是游戏的借口,或许阿呆真的呆了,以至于知识只是在游戏的水平上;无所谓啦,生活本是游戏,傻傻的享受生活,岂能被生活所扰。

日志

QtWidget: 给widget加上背景图

已有 2254 次阅读2012-3-1 02:16 |个人分类:Qt系列|系统分类:嵌入式系统

 QPalette palette;
palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
widget->setPalette(palette);
帮助文档里面如上面所列代码,但是使用这种写法,图片没有缩放,
添加以下代码即可完成完美显示:

widget->setAutoFillBackground(true); // 这句要加上, 否则可能显示不出背景图.


QPalette palette = widget->palette();


palette.setBrush(QPalette::Window,


                      QBrush(QPixmap("1.png").scaled( // 缩放背景图.


                              widget->size(),


                              Qt::IgnoreAspectRatio,


                              Qt::SmoothTransformation))); // 使用平滑的缩放方式


widget->setPalette(palette); // 至此, 已给widget加上了背景图.




路过

鸡蛋

鲜花

握手

雷人

发表评论 评论 (2 个评论)

回复 adaiplay 2012-3-4 14:48
转: 一. 背景刷成黑色,前景色设为白色。 方法一、paltette方式,经测试,该方法不会影响到其他控件,推荐使用 QPalette bgpal = palette(); bgpal.setColor (QPalette::Background, QColor (0, 0 , 0, 255)); //bgpal.setColor (QPalette::Background, Qt::transparent); bgpal.setColor (QPalette::Foreground, QColor (255,255,255,255)); setPalette (bgpal); 方法二、stylesheet方式 影响子控件的方法是: setStyleSheet ("background-color: rgb(0,0,0);color: rgb(255,255,255);"); 不影响子控件的方法是: setStyleSheet ("venus--TitleBar {background-color: rgb(0,0,0);color: rgb(255,255,255);}"); 二. 圆角控件 用stylesheet方式 setStyleSheet ("border:2px groove gray;border-radius:10px;padding:2px 4px;"); 三. 圆角窗口 RoundRectWin::RoundRectWin() { QPalette p = palette(); QPixmap img("roundrect.png"); QBitmap mask("roundrect_mask.png"); p.setBrush(QPalette::Window, QBrush(img)); setPalette(p); setMask(mask); resize(img.size()); //setWindowFlags(Qt::FramelessWindowHint);//这句会去掉标题栏 } 注意:mask的图多余部分设为白色
回复 adaiplay 2012-3-4 14:49
转: 一. 背景刷成黑色,前景色设为白色。 方法一、paltette方式,经测试,该方法不会影响到其他控件,推荐使用 QPalette bgpal = palette(); bgpal.setColor (QPalette::Background, QColor (0, 0 , 0, 255)); //bgpal.setColor (QPalette::Background, Qt::transparent); bgpal.setColor (QPalette::Foreground, QColor (255,255,255,255)); setPalette (bgpal); 方法二、stylesheet方式 影响子控件的方法是: setStyleSheet ("background-color: rgb(0,0,0);color: rgb(255,255,255);"); 不影响子控件的方法是: setStyleSheet ("venus--TitleBar {background-color: rgb(0,0,0);color: rgb(255,255,255);}"); 二. 圆角控件 用stylesheet方式 setStyleSheet ("border:2px groove gray;border-radius:10px;padding:2px 4px;"); 三. 圆角窗口 RoundRectWin::RoundRectWin() { QPalette p = palette(); QPixmap img("roundrect.png"); QBitmap mask("roundrect_mask.png"); p.setBrush(QPalette::Window, QBrush(img)); setPalette(p); setMask(mask); resize(img.size()); //setWindowFlags(Qt::FramelessWindowHint);//这句会去掉标题栏 } 注意:mask的图多余部分设为白色