2016-04-21 17 views
1

我正在嘗試在我的項目中創建一個QPushButton,以便文本顯示在自定義按鈕圖像或圖標的頂部。 我嘗試以下方法:如何用圖標上顯示的文本創建QPushButton?

imagePath = path; 
QPixmap pixmap(imagePath); 
QIcon ButtonIcon(pixmap); 
button->setIcon(ButtonIcon); 
button->setIconSize(pixmap.rect().size()); 
button->setGeometry(0,0,height,width); 
button->setStyleSheet(
    "background-color: gray;" 
    "border: 1px solid black;" 
    "border-radius: "+QString::number(radius)+"px;" 
    "color: lightGray; " 
    "font-size: 25px;" 
    ); 

當我嘗試在這裏使用的setText,它顯示的圖標第一和文字上其右。我希望文字出現在圖標上方。

我也嘗試下面的方法我在網上找到:

imagePath = path; 
button->setGeometry(0,0,height,width); 
button->setStyleSheet("background-image: url(:/images/images/2adjacentTracksButton.png));" 
         "background-position: center center"); 

這一個不接受我的URL路徑,因此不顯示我需要的按鈕上的圖像。

我該如何解決這個問題?

+0

您在QSS表達式中'2adjacentTracksButton.png'後面有''''。 – hank

回答

0

當涉及到操縱按鈕,你可能想要做你自己的班級,這將實施QAbstractButton。事情是這樣的:

class MyButton : public QAbstractButton 
{ 
    Q_OBJECT 

public: 
    static MyButton* createButton(QIcon icon, QWidget *parent); 
    ~MyButton(); 

    void setText(QString); 
    void setIcon(eIcon); 
    void setOrientation(Qt::Orientation); 

protected : 
    MyButton(QWidget *parent); 

    // here, you can reimplement event like mousePressEvent or paintEvent 

private : 
    QBoxLayout* m_ButtonLayout; 
    QLabel*  m_IconLabel; 
    QIcon  m_Icon; 
    QLabel*  m_TextLabel; 
} 

.cpp

MyButton* button = MyButton::createButton(myButtonIcon, this); 

這僅僅是一個基本的:

MyButton::MyButton(QWidget *parent) 
    : QAbstractButton(parent) 
{  
    m_ButtonLayout = new QBoxLayout(QBoxLayout::LeftToRight, this); 
    m_ButtonLayout->setAlignment(Qt::AlignCenter); 
    m_ButtonLayout->setContentsMargins(0, 0, 0, 0); 
    m_ButtonLayout->setSpacing(1); 

    m_IconLabel = new QLabel(this); 
    m_IconLabel->setAlignment(Qt::AlignCenter); 
    m_ButtonLayout->addWidget(m_IconLabel); 

    m_TextLabel = new QLabel(this); 
    m_TextLabel->setAlignment(Qt::AlignCenter); 
    m_ButtonLayout->addWidget(m_TextLabel); 
    //m_TextLabel->hide(); 
} 

MyButton* MyButton::createButton(QIcon icon, QWidget *parent) 
{ 
    MyButton* pButton = new MyButton(parent); 
    pButton->setIcon(icon); 

    return pButton; 
} 

void MyButton::setText(QString text) 
{ 
    m_TextLabel->setVisible(!text.isEmpty()); 
    m_TextLabel->setText(text); 
    QAbstractButton::setText(text); 
} 

void MyButton::setIcon(QIcon icon) 
{ 
    m_Icon = icon; 
    m_IconLabel->setVisible(true); 
} 

void MyButton::setOrientation(Qt::Orientation orientation) 
{ 
    if (orientation == Qt::Horizontal) 
     m_ButtonLayout->setDirection(QBoxLayout::LeftToRight); 
    else 
     m_ButtonLayout->setDirection(QBoxLayout::TopToBottom); 
} 

現在你可以通過調用靜態方法來創建你的圖標,你的按鈕我給你的例子,我不確定它會起作用(這是我以前做過的事情),但你可以試試它。希望有所幫助!

相關問題