How to add both an image and text to a QLabel

扶醉桌前 提交于 2020-01-02 07:23:08

问题


I have a QHBoxLayout with a QLabel in it, and I'm trying to get both an icon and window title text in the QLabel. Is that possible? Or even to add the icon directly to the QHBoxLayout, so that is is laying just before the window title text?

Here is my code:

class MyBar(QWidget):

   def __init__(self, parent):
       super(MyBar, self).__init__()
       self.parent = parent
       self.layout = QHBoxLayout()
       self.layout.setContentsMargins(0,0,0,0)
       self.title = QLabel("Main Window")

   def changetitle(self, msg):
       self.title.setText(msg)

Edit:

Here is the code where I used two labels side by side:

    self.label3 = QLabel(self)
    self.title = QLabel("Main Window")
    self.pixmap = QPixmap('res/myIcon.ico')
    self.label3.setPixmap(self.pixmap)
    self.label3.setAlignment(Qt.AlignCenter)
    self.title.setFixedHeight(35)
    self.title.setAlignment(Qt.AlignCenter)
    self.layout.addWidget(self.label3)
    self.layout.addWidget(self.title)
    self.label3.setStyleSheet("""
        background-color: black;
    """)
    self.title.setStyleSheet("""
        background-color: black;
        color: white;
    """)

回答1:


Below is a demo based on your code that should do what you want:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QHBoxLayout(self)
        self.label3 = QLabel(self)
        self.title = QLabel("Wild Lion's Browser")
        self.pixmap = QPixmap('icon48.png')
        self.label3.setPixmap(self.pixmap)
        self.label3.setAlignment(Qt.AlignCenter)
        self.title.setMinimumHeight(self.pixmap.height())
        self.title.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label3)
        layout.addWidget(self.title)
        self.label3.setStyleSheet("""
            background-color: black;
        """)
        self.title.setStyleSheet("""
            background-color: black;
            color: white;
            padding: 0px 10px 0px 10px;
        """)
        layout.setSpacing(0)
        layout.addStretch()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 200, 30)
    window.show()
    sys.exit(app.exec_())


来源:https://stackoverflow.com/questions/47856872/how-to-add-both-an-image-and-text-to-a-qlabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!