Qt2.2.0 透明的 QPushButton

    技术2022-05-20  53

    基本思路:

    1.将父窗口的背景拷贝到pushbutton的背景中;

    2.重写paintEvent()方法;

     

     

     

    目前存在一个缺点,当动态移动时需要手动刷新pushbutton的背景,因为背景拷贝是在构造函数完成的。

    待续完善 .....

     

    a) TPushButton.h文件

     

    #ifndef TPUSHBUTTON_H #define TPUSHBUTTON_H #include <qpushbutton.h> class TPushButton: public QPushButton { private:     QString m_picture;         public:     TPushButton( QWidget *parent, const char *name=0 );         void SetBackground(const QString& );     void paintEvent( QPaintEvent * ); }; #endif

     

    b) TPushButton.cpp文件

    #include <qpainter.h> #include <stdio.h> #include <unistd.h> #include "../debug/debug.h" #include "TPushButton.h" #if 1 #define _debug_btn #endif #ifdef _debug_btn #define debug_btn(fmt,...) debug(fmt,##__VA_ARGS__) #else #define debug_btn(fmt,...) #endif TPushButton::TPushButton( QWidget *parent, const char *name ) : QPushButton( parent, name ) { #if 1     setBackgroundPixmap(*parentWidget()->backgroundPixmap());     setBackgroundOrigin(QWidget::ParentOrigin); //当有多个父控件时可使用绝对坐标,QWidget::WindowOrigin或QWidget::AncestorOrigin #else     setAutoMask(TRUE);     setBackgroundMode(NoBackground); #endif        } void TPushButton::SetBackground(const QString& picture)                  {     m_picture = picture; }    void TPushButton::paintEvent( QPaintEvent *event ) {     debug_btn("paintEvent/n");     QPainter paint(this);     QPixmap *icon = new QPixmap(m_picture);         if(m_picture==""){         debug_btn("drawButton/n");         drawButton( &paint );     }else     {         int x1, y1, x2, y2;         rect().coords( &x1, &y1, &x2, &y2 );                 if(isDown())         {             debug_btn("draw rect/n");                         QColorGroup g = colorGroup();                     paint.setPen( g.foreground() );             paint.setBrush( QBrush(g.button(),NoBrush) );                 erase( event->region() );             paint.drawPixmap( 1, 1, *icon );             drawButtonLabel(&paint);                 paint.setPen( QColor(80,80,80) );//g.shadow()             paint.drawRect( x1, y1, x2-x1+1, 1 );             paint.drawRect( x1, y1, 1, y2-y1+1 );                         paint.setPen( QColor(250,250,250) );//g.shadow()             paint.drawRect( x1, y2, x2-x1+1, 1 );             paint.drawRect( x2, y1, 1, y2-y1+1 );         }else{                        debug_btn("drawPixmap/n");             erase( event->region() );             paint.drawPixmap( 0, 0, *icon );             drawButtonLabel(&paint);         }                         if ( hasFocus() ) {              QRect r(x1, y1, x2-x1, y2-y1);              style().drawFocusRect( &paint, r , colorGroup(), &colorGroup().button() );         }       }     delete icon; }


    最新回复(0)