Software and hardware environment
- Windows 10 64bit
- Anaconda3 with python 3.8
- PyQt5 5.15
Introduction
By default, when a large amount of text is displayed on a label
, the part that cannot be displayed is truncated. At this time, what naturally comes to mind is how to make the text display appear in the form of a scroll bar, so that dragging the scroll bar can display the part that cannot be displayed by the label
control. This article will take a look at how to solve this problem.
Practical
The QScrollArea
is used here, which is a control container. Put the corresponding control (such as the label
in this article) into the QScrollArea
to achieve the effect of the scroll bar.
Let’s see a specific example
import sys from PyQt5.QtWidgets import QWidget, QLabel, QScrollArea, QApplication, QVBoxLayout, QMainWindow from PyQt5.QtCore import Qt class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): # 实例化滚动区域self.scrollarea = QScrollArea() self.widget = QWidget() # 垂直布局self.vboxlayout = QVBoxLayout() for i in range(0, 10): # label显示的文本label = QLabel("This is a label.") # label加入到垂直布局中self.vboxlayout.addWidget(label) # 第四个label中显示xml文件的内容if i == 3: # 读取test.xml文件的内容并显示在label上with open('test.xml', encoding='UTF-8') as f: text_label = f.read() label.setText(text_label) self.widget.setLayout(self.vboxlayout) # 设置滚动条的属性self.scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.scrollarea.setWidgetResizable(True) self.scrollarea.setWidget(self.widget) # 居中self.setCentralWidget(self.scrollarea) self.setGeometry(600, 100, 1000, 900) self.setWindowTitle('PyQt5 Label滚动条示例') self.show() if __name__ == '__main__': app = QApplication(sys.argv) main = MainWindow() sys.exit(app.exec_())
code execution result
Source code download
https://github.com/xugaoxiang/learningPyQt5
PyQt5 series of tutorials
For more PyQt5
tutorials, please move to
https://xugaoxiang.com/category/python/pyqt5/
This article is transferred from https://xugaoxiang.com/2022/12/04/pyqt5-36-make-label-scrollable/
This site is only for collection, and the copyright belongs to the original author.