更改QLabel的形状

时间:2019-05-05 16:27:35

标签: pyqt5

我需要一点帮助,我试图创建一个聊天室,但是我希望用来显示消息的QLabel具有这样的消息容器形式

enter image description here

不仅具有QLabel的典型正方形形状

我尝试执行以下操作:

def CreateLabel(self):
    image = QtGui.QPixmap("container.png")
    mask = image.createMaskFromColor(QtCore.Qt.red)

    self.Label = QLabel()
    self.Label.setText("Test Text")
    self.Label.setAlignment(QtCore.Qt.AlignRight)
    self.Label.setMask(mask)

1 个答案:

答案 0 :(得分:1)

尝试一下:

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


class Label(QLabel):
    def __init__(self, text):
        super().__init__()

        self.text = text

        self.im = QImage('D:/_Qt/img/chat.png')
        self.resize(self.im.size())

    def paintEvent(self, event):
        super().paintEvent(event)

        p = QPainter(self)
        p.drawImage(0, 0, self.im)

        self.drawText(event, p)                                 

    def drawText(self, event, p):
        p.setPen(QColor(168, 34, 4))
        p.setFont(QFont('Decorative', 12))
        p.drawText(event.rect(), Qt.AlignTop, self.text) 

    def closeEvent(self, event):
        quit()


class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.text = """
                        How to draw a QLabel with chat image.
                    I would like a little help, I am trying to generate a chat 
                    room but I would like that the QLabel that I use to show 
                    the messages had the form of a message container like this.
                    """        

        self.label = Label(self.text)
        self.label.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
#    w.show()
    app.exec_()

enter image description here