[Qt-interest] How can I change a button's background?

Kermit Mei kermit.mei at gmail.com
Fri Jun 19 11:41:07 CEST 2009


Hello community!

How can I change a button's background? 

I know I can use styleSheet, but, my problem is that there're so many
buttons, and every button's background may be change by the users at
running time, and their background may not be the same. Also, I must
remember the last background changed by user, and reload them at the
next running time.

How Can I do it? I what to use paintEvent() to do it, but when I repaint
the background, I can't see any different effect when I press the
buttons. My code is like this: 

//The Header file:
#ifndef _REMOTEBUTTON_H
#define _REMOTEBUTTON_H

#include <QPushButton>
#include <QString>

class QPixmap;

class RemoteButton : public QPushButton
{
  Q_OBJECT
public:
  RemoteButton(QWidget *parent = 0);
  ~RemoteButton();

  void setBackGround(const QString picFile);

protected:
  void paintEvent(QPaintEvent *event);
  QPixmap *pixmap;
};

#endif //_REMOTEBUTTON_H


//The source file:
#include <QPen>
#include <QPainter>
#include <QLabel>
#include <QPixmap>

#include "RemoteButton.h"

RemoteButton::RemoteButton(QWidget *parent)
  :QPushButton(parent),pixmap(0)
{
  //Do Nothing Here!
}

RemoteButton::~RemoteButton() {
  if(pixmap != 0)
    delete pixmap;
}

void RemoteButton::setBackGround(const QString picFile) {
  if( pixmap != 0)
    delete pixmap;
  pixmap = new QPixmap(picFile);
}

void RemoteButton::paintEvent(QPaintEvent *event) {
  if(pixmap != 0) {
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),*pixmap);
  }else
    QPushButton::paintEvent(event);
}


//The test main.cpp file
#include <QApplication>
#include "RemoteButton.h"

int main(int argc,char *argv[])
{
  QApplication app(argc,argv);
  RemoteButton rBtn;
  rBtn.setBackGround("./bk.png");
  rBtn.show();
  return app.exec();
}


It can works, but I can't see and different effects when I press it.

Hope your help.
Thanks:)

Kermit




More information about the Qt-interest-old mailing list