如何将图像和文本都添加到QLabel [英] How to add both an image and text to a QLabel

查看:48
本文介绍了如何将图像和文本都添加到QLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有QLabel的QHBoxLayout,并且我试图在QLabel中同时获取图标和窗口标题文本.那可能吗?甚至直接将图标添加到QHBoxLayout中,以便将其放置在窗口标题文本之前?

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?

这是我的代码:

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)

这是我并排使用两个标签的代码:

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;
    """)

推荐答案

下面是一个基于您的代码的演示,该演示应执行您想要的操作:

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_())

这篇关于如何将图像和文本都添加到QLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆