Derive a window from Qwidget, use stylesheet to set the background, there is no problem with the designer settings, or, with the Setstylesheet () setting, the code action is correct, and after the compilation runs, there is no background.
The following is an example of validation (through code validation, no designer is used):
The project directory structure is as follows:
The Mywidget.h sample code is as follows:
#ifndef mywidget_h#define mywidget_h#include <qwidget>class mywidget:public qwidget{ Q_OBJECTpublic: Mywidget (Qwidget *parent = 0); ~mywidget ();}; #endif//Mywidget_h
The Mywidget.cpp sample code is as follows:
#include "mywidget.h" Mywidget::mywidget (Qwidget *parent) : Qwidget (parent) {/ /set a background map to a window via a style sheet //" Mywidget "for Class name //". /test/test.jpg ": For the picture path, relative to the executable program's relative path this->setstylesheet (". Mywidget{background-image:url (.. /test/test.jpg);} ");} Mywidget::~mywidget () {}
The main.cpp sample code is as follows:
#include "mywidget.h" #include <qapplication>int main (int argc, char *argv[]) { qapplication A (argc, argv); Mywidget W; W.show (); return a.exec ();}
after the compilation is run, the background of the window is not set successfully:
The reason is that Qwidget's PaintEvent () is empty, and the stylesheet is drawn to the window through paint, and we need to re-write the PaintEvent () function in order to actually implement the inheritance.
The solution is as follows:
Mywidget.h Add the following code:
. h file//Add paintevent () Declaration protected:void PaintEvent (qpaintevent *); Rewrite PaintEvent ()
Mywidget.cpp Add the following code:
. cpp file//rewrite paintevent () void Mywidget::p aintevent (qpaintevent *) { qstyleoption opt;//requires header file # include < Qstyleoption> Opt.init (this); Qpainter p (this); Requires header file # include <QPainter> style ()->drawprimitive (qstyle::P e_widget, &opt, &p, this);}
Recompile run, find the background map setting is successful:
This tutorial sample code download Please click this link: Http://download.csdn.net/detail/tennysonsky
Reference: http://blog.csdn.net/dbzhang800
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Workaround for Qwidget direct derived class style sheet does not work