2012-07-20 142 views
1

我需要在图像顶部显示一个按钮。类似的东西,以Qt图像顶部的显示按钮

的背景是一个的QPixmap/QImage的和按钮是一个QPushbutton。我需要能够动态更改图像 - 所以我不确定样式表是否适合该任务。我试过this,但无法让它工作。

任何解决方案?

回答

3
  1. 子类QWidget并实现paintEent,您可以在后台绘制图像。通过样式表设置和更改背景图片也是可能的。
  2. 用按钮添加布局到这个小部件。

有这样的事情:

class WidgetWithButton 
    : public QWidget 
{ 
    Q_OBJECT 
    QImage m_bgImage; 
public: 
    WidgetWithButton(QWidget* aParent) 
    : QWidget(aParent) 
    { 
    QHBoxLayout* l = new QHBoxLayout(this); 
    QPushButton* myButton = new QPushButton(tr("Close")); 
    l->addWidget(myButton, 0, Qt::AlignCenter); 
    } 
    void setImage(const QImage& aImage) 
    { 
    m_image = aImage; 
    update(); 
    } 
protected: 
    virtual void paintEvent(QPaintEvent* aPainEvent) 
    { 
    if (m_image.isValid()) 
    { 
     QPainter painter(this); 
     painter.drawImage(rect(), m_image); 
    } 
    else 
     QWidget::paintEvent(aPainEvent); 
    } 
}; 
+0

就像一个魅力。谢谢! – go4sri 2012-07-21 10:24:23