今天使用qt时,想定义一个背景图,采用了比较通常的办法,使用QPalette:
QPalette palette = this->palette();
ui->setupUi(this);
palette.setBrush(QPalette::Background,
QBrush(QPixmap("../static/test.jpg").scaled(this->size()))); // 使用平滑的缩放方式
this->setPalette(palette);
为了监听窗口变化,重写了paintEvent,在其中也加入这段代码,但这带来了paintEvent的递归调用的问题,CPU的占用率明显异常,该函数被持续调用,通过新增一个窗口尺寸判断,问题解决
void MainWindow::paintEvent(QPaintEvent *event) {
Q_UNUSED(event);
static QSize temp;
if(temp.height() == this->size().height() && temp.width() == this->size().width()){
return;
}
temp = this->size();
QPalette palette = this->palette();
palette.setBrush(QPalette::Background,
QBrush(QPixmap("../static/image/test.jpg").scaled(this->size()))); // 使用平滑的缩放方式
this->setPalette(palette);
cout << "event" << endl;
}