PyQt5 label centered display picture (QLabel)

First of all! ! ! ! Answer the content of the title:

I need to add a line of code

#别忘了引入欧
from PyQt5.QtCore import Qt
self.label.setAlignment(Qt.AlignCenter) 

PyQt5 tags commonly used methods to display pictures

General introduction

QLabel widgets provide text or image display.
QLabel is used to display text or images. No user interaction function is provided. The appearance of the label can be configured in various ways and can be used to specify the focus mnemonic key of another widget.
QLabel can contain any of the following content types:
Insert picture description here
when the content is changed using any method, any previous content is cleared.

Warning: When using setText() to set text content in QLabel, QLabel will try to guess whether it displays the text as plain text or rich text as part of HTML 4 markup. If you want to explicitly display the text format, call setTextFormat(), for example, if you want the text to be in plain text format, but you cannot control the text source (for example, when displaying data loaded from the Web).
By default, the label displays left-aligned, vertically centered text and images. The appearance of QLabel can be adjusted and fine-tuned in many ways.
You can use setAlignment() and setIndent() to adjust the content positioning within the QLabel widget area. Text content can also be wrapped along word boundaries using setwordpwrap ().
For example, this code sets a sunken panel with two lines of text in the lower right corner (two lines are flush with the right side of the label):

label = QLabel(self)
label.resize(200,100)
label.setFrameStyle(QFrame.Panel | QFrame.Sunken)
label.setText("first line\nsecond line")
label.setAlignment(Qt.AlignBottom | Qt.AlignRight)
QLabel从QFrame继承的属性和函数,也可以用来指定要用于任何给定标签的构件框架。

For more introduction, please refer to the official website

Small example of QLabel

Insert picture description here

核心代码如下:
class Example(QWidget):

    def initUI(self):

        self.lb1 = QLabel('学点编程吧,我爱你~!',self)
        self.lb2 = QLabel('我内容很少哦...',self)
        self.lb3 = QLabel('我内容很少哦...',self)
        self.lb3.setWordWrap(True)

        self.bt1 = QPushButton('输入内容1',self)
        self.bt2 = QPushButton('输入内容2',self)


        self.ra1 = QRadioButton('左边',self)
        self.ra2 = QRadioButton('中间',self)
        self.ra3 = QRadioButton('右边',self)

        self.bg1 = QButtonGroup(self)
        self.bg1.addButton(self.ra1, 1)
        self.bg1.addButton(self.ra2, 2)
        self.bg1.addButton(self.ra3, 3)

        self.show()

        self.bg1.buttonClicked.connect(self.rbclicked)
        self.bt1.clicked.connect(self.showDialog)
        self.bt2.clicked.connect(self.showDialog)

    def rbclicked(self):
        if self.bg1.checkedId() == 1:
            self.lb1.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        elif self.bg1.checkedId() == 2:
            self.lb1.setAlignment(Qt.AlignCenter)
        elif self.bg1.checkedId() == 3:
            self.lb1.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
    
    def showDialog(self):
        sender = self.sender()
            if sender == self.bt1:
                text, ok = QInputDialog.getText(self, '内容1', '请输入内容1:')
                if ok:
                    self.lb2.setText(text)
            elif sender == self.bt2:
                text, ok = QInputDialog.getText(self, '内容2', '请输入内容2:')
                if ok:
                    self.lb3.setText(str(text))

This example mainly implements two functions:
QLabel content alignment: here we give three: left center, center, and right center.
When QLabel has a lot of content, the content inside can wrap. Here we compare it with two input dialogs.

self.lb3 = QLabel('我内容很少哦...',self)
self.lb3.setWordWrap(True)

Set the attribute of WordWrap to True to realize automatic line wrapping. By default, automatic line wrapping is not possible.

def rbclicked(self):
    if self.bg1.checkedId() == 1:
        self.lb1.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)    elif self.bg1.checkedId() == 2:
        self.lb1.setAlignment(Qt.AlignCenter)    elif self.bg1.checkedId() == 3:
        self.lb1.setAlignment(Qt.AlignVCenter | Qt.AlignRight)

When we click on different radio buttons, the contents of the QLabel will be aligned accordingly. By default, the content of the label is left-aligned and vertically centered. The other situation is as follows: It contains horizontal and vertical signs, which can be combined to produce the desired effect.
The horizontal mark is: the
Insert picture description here
vertical mark is:
Insert picture description here
special:
Qt.AlignCenter: horizontal and vertical centering. At
most one horizontal and one vertical mark can be used at a time. Of course, there are exceptions, and the following can show two properties.

Insert picture description here

部分核心代码如下:
class Example(QWidget):
    def initUI(self):

        lb = QLabel(self)

        html = '''
                <style type="text/css">
                    table.imagetable {
                        font-family: verdana,arial,sans-serif;
                        font-size:11px;
                        color:#333333;
                        border-width: 1px;
                        border-color: #999999;
                        border-collapse: collapse;
                    }
                  #...里面众多的CSS内容,我就省略了,节约空间
            '''
        lb.setText(html)
        self.show()

PyQt5's text widget can display rich text, which is specified by a subset of HTML4 tags. For specific content, please refer to the official document: https://doc.qt.io/qt-5/richtext-html-subset .html, the commonly used HTML tags and CSS attributes are supported.

Picture presentation

部分核心代码如下:
class Example(QWidget):
    def initUI(self):

        pix = QPixmap('sexy.jpg')

        lb1 = QLabel(self)
        lb1.setGeometry(0,0,300,200)
        lb1.setStyleSheet("border: 2px solid red")
        lb1.setPixmap(pix)

        lb2 = QLabel(self)
        lb2.setGeometry(0,250,300,200)
        lb2.setPixmap(pix)
        lb2.setStyleSheet("border: 2px solid red")
        lb2.setScaledContents(True)

The picture demonstration is a comparative demonstration.

We first use QPixmap() to create a QPixmap object, and then insert it into the two QLabel objects. The difference is:

We insert lb1 directly into
lb2, and we enable setScaledContents(True). The meaning of this function is whether to scale its content to fill all available space. When enabled, the label displays a pixmap, which will scale the pixmap to fill the available space. The default value of this attribute is False.
setStyleSheet() is for everyone to check the size range of the label we set. For a detailed explanation, please see the previous chapter "LCD Display".

Animation presentation

部分核心代码如下:

class Example(QWidget):

    def initUI(self):

        self.lb = QLabel(self)
        self.lb.setGeometry(100,50,300,200)

        self.bt1 = QPushButton('开始',self)
        self.bt2 = QPushButton('停止',self)

        self.pix = QPixmap('movie.gif')
        self.lb.setPixmap(self.pix)
        self.lb.setScaledContents(True)

        self.bt1.clicked.connect(self.run)
        self.bt2.clicked.connect(self.run)

        self.show()
    def run(self):
        movie = QMovie("movie.gif")
        self.lb.setMovie(movie)
        if self.sender() == self.bt1:
            movie.start()
        else:
            movie.stop()
            self.lb.setPixmap(self.pix)

Unexpectedly, QLabel also has this brutal skill, which plays animation. . .
The key to this code is the use of QMovie, let's briefly introduce it.
The QMovie class is a convenient class for playing animation with QImageReader.
This class is used to display simple animations without sound. If you want to display video and media content, please use the Qt multimedia framework instead.

First, let's create a QMovie object. Before starting the movie, you can call isValid() to check whether the image data is valid. To start the movie, call start(). QMovie will enter the running state and issue start() and stateChanged(). To get the current state of the movie, call state().
To display the movie in the application, you can pass the QMovie object to QLabel.setMovie(). example:

label = QLabel(self)
movie = QMovie("animations/fire.gif")
label.setMovie(movie)
movie.start()

Whenever there is a new frame in the movie, QMovie will send an updated() signal. If the size of the frame changes, the resized() signal is issued. You can call currentImage() or currentPixmap() to get a copy of the current frame. When the movie is finished, QMovie issues finished(). If an error occurs during playback (that is, the image file is damaged), QMovie will issue an error().
You can control the speed of movie playback by calling setSpeed(). SetSpeed() takes the percentage of the original speed as a parameter. Pause the movie by calling setPaused (True). QMovie will enter the paused state and issue stateChanged(). If you call setPaused(False), QMovie will re-enter the running state and start the movie again. To stop the movie, use stop().
Some animation formats allow you to set the background color. You can call setBackgroundColor() to set the color, or call backgroundColor() to get the current background color.
currentFrameNumber() returns the serial number of the current frame. If the image format is supported, frameCount() will return the total number of frames in the animation. You can call loopCount() to get the number of times the movie should loop before it completes. nextFrameDelay() returns the number of milliseconds that the current frame should be displayed.
You can instruct QMovie to cache animation frames by calling setCacheMode().
Call supportedFormats() to get a list of formats supported by QMovie.

def run(self):
    movie = QMovie("movie.gif")
    self.lb.setMovie(movie)
    if self.sender() == self.bt1:
        movie.start()
    else:
        movie.stop()
        self.lb.setPixmap(self.pix)

This function is very simple. When we click the "Start" button, the animation is played; when the "Stop" button is clicked, the animation is stopped.

Reprinted at: https://zhuanlan.zhihu.com/p/32134728

Guess you like

Origin blog.csdn.net/lockhou/article/details/113408429