1. 程式人生 > >Qt學習筆記:QLabel同時顯示圖片和文字

Qt學習筆記:QLabel同時顯示圖片和文字

環境

系統:Windows10 64位 家庭中文版
Qt版本:5.6.0 msvc2013 64位
編譯器:Visual Studio 2013 專業版

前言

QLabel是Qt自帶的一個顯示用控制元件,可以用來顯示圖片和文字。其使用也非常方便:用setPixmap(const QPixmap &)介面來設定要顯示的圖片,用setText(const QString &)介面來設定要顯示的文字。然而在使用過程中,我發現QLabel的setPixmap(const QPixmap &)和setText(const QString &)是互斥的,即兩個同時設定時,只有一個生效(最後設定的那個生效)。
示例程式碼及現象如下:

    m_pLblPixmap = new QLabel(this);
    m_pLblPixmap->resize(200, 200);
    m_pLblPixmap->move(0, 0);
    m_pLblPixmap->setAlignment(Qt::AlignCenter);
    m_pLblPixmap->setScaledContents(true);
    //我這邊兩個介面都呼叫,但是最後呼叫的setPixmap覆蓋了setText
    m_pLblPixmap->setText("This is pixmap");
    m_pLblPixmap->
setPixmap(QPixmap(":/image/bg.jpg")); m_pLblText = new QLabel(this); m_pLblText->resize(200, 200); m_pLblText->move(m_pLblPixmap->x() + m_pLblPixmap->width() + 2, 0); m_pLblText->setAlignment(Qt::AlignCenter); m_pLblText->setScaledContents(true); //我這邊兩個介面都呼叫,但是最後呼叫的setText覆蓋了setPixmap
m_pLblText->setPixmap(QPixmap(":/image/bg.jpg")); m_pLblText->setText("This is text");

最後設定的生效

解決方法

用樣式表設定背景圖片,用setText(const QString &)設定文字,示例程式碼及現象如下:

    m_pLblStyleSheet = new QLabel(this);
    m_pLblStyleSheet->resize(200, 200);
    m_pLblStyleSheet->move(m_pLblText->x() + m_pLblText->width() + 2, 0);
    m_pLblStyleSheet->setScaledContents(true);
    m_pLblStyleSheet->setAlignment(Qt::AlignCenter);
    //這個不會適應圖片,可能出現圖片顯示不全或者無法充滿整個QLabel
//    m_pLblStyleSheet->setStyleSheet(QString("background-image:url(:/image/bg.jpg)"));
    //這個會自動適應圖片,我這裡還設定了文字的顏色
    m_pLblStyleSheet->setStyleSheet(QString("border-image:url(:/image/bg.jpg);color:rgb(128,128,128);"));
    m_pLblStyleSheet->setText("This is style sheet");

圖片和文字同時顯示