这个简单的封装有BUG,就是内存释放不掉的BUG 大家帮我看看问题出现在那,当然还有其他问题也可以帮忙指出
.h
- C/C++ code
#pragma once #include <QPushButton> #include <QImage> #include <QPixmap> #include <QSize> #include <QIcon> #include <QPaintEvent> #include <QPainter> #include <QColor> class IButton : public QPushButton { Q_OBJECT public: IButton(QWidget * parent = 0); ~IButton(void); void setBlack(QString & name); void wordshow(QString &show_word); void set_font_size(); public: QString word_; protected: QImage *image_; QIcon *icon_; QPixmap *pixmap_; protected: void paintEvent( QPaintEvent * event ); };
- C/C++ code
#include "IButton.h" IButton::IButton(QWidget * parent) :QPushButton(parent) { int h; QPalette palette_;// = palette(); palette_ = palette(); QFont font_ = font(); image_ = new QImage(); pixmap_ = new QPixmap(); icon_ = new QIcon(); word_.clear(); h = size().width()>size().height()?size().height():size().width(); font_.setPointSize(h-h/3); setFont(font_); palette_.setColor(QPalette::Active,QPalette::ButtonText,QColor(255,255,255)); setPalette(palette_); setFocusPolicy(Qt::NoFocus); } IButton::~IButton(void) { delete []image_; delete []pixmap_; delete icon_; } void IButton::setBlack(QString & name) { image_->load(name); QSize s = size();//the button you would to set the back; QImage i2 = image_->scaled(s);//adapt the size of button; *pixmap_ = QPixmap::fromImage(i2);//this is the static function setIcon(QIcon(*pixmap_)); setIconSize(s); } void IButton::paintEvent(QPaintEvent * event) { QPushButton::paintEvent(event) ; QPainter painter(this) ; if (!word_.isEmpty()) { painter.drawText(rect(),Qt::AlignCenter,word_); } event->accept(); return ; } void IButton::wordshow(QString &show_word) { word_ = show_word; } void IButton::set_font_size() { }
现在问题如下:
如果我用这个类作为button装载图片,来响应按键被按下和放开,那么按下一个背景,放开一个背景。其他没问题但我不断的按下放开内存在不断的增长,即使我在主窗口中delete 这个button 内存还是回不去。问题出现在那边?
------解决方案--------------------
试试setAttribute(Qt::WA_DeleteOnClose, true);
我以前也遇到过内存不能释放的问题,不管delete还是写析构函数都不管用,后来用这个函数问题解决了,楼主试试吧