PyQt5可滚动标签 – 设置工具提示
在这篇文章中,我们将看到如何为可滚动的标签设置工具提示。默认情况下,当我们创建一个标签时,所有的文本都是单行的,如果文本的长度大于标签的长度,额外的文本就不会显示,尽管在setWordWrap方法的帮助下,我们可以创建一个多行的标签,但如果文本超过了标签,仍然不会显示。为了在一个小标签中显示整个文本,我们必须使标签可滚动,为了做到这一点,我们必须建立自己的可滚动标签类,它继承了QScrollArea类,使我们可以使标签可滚动。
实现的步骤 –
- 创建一个继承于QScrollArea的新类
- 在该类中创建垂直布局
- 创建一个标签,使其成为多行,并将其添加到布局中
- 覆盖标签的setText和text方法
- 在主窗口类中创建该类的对象,并为其设置文本
- 在setToolTip方法的帮助下,为该对象添加工具提示。
下面是实现的过程
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
# class for scrollable label
class ScrollLabel(QScrollArea):
# constructor
def __init__(self, *args, **kwargs):
QScrollArea.__init__(self, *args, **kwargs)
# making widget resizable
self.setWidgetResizable(True)
# making qwidget object
content = QWidget(self)
self.setWidget(content)
# vertical box layout
lay = QVBoxLayout(content)
# creating label
self.label = QLabel(content)
# making label multi-line
self.label.setWordWrap(True)
# adding label to the layout
lay.addWidget(self.label)
# the setText method
def setText(self, text):
# setting text to the label
self.label.setText(text)
# getting text method
def text(self):
# getting text of the label
get_text = self.label.text()
# return the text
return get_text
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 600, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# text to show in label
text = "There are so many options provided by Python to develop GUI " \
" There are so many options provided by Python to develop GUI" \
" There are so many options provided by Python to develop GUI"
# creating scroll label
label = ScrollLabel(self)
# setting text to the label
label.setText(text)
# setting geometry
label.setGeometry(100, 100, 150, 80)
# setting tool tip
label.setToolTip("It is tool tip")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出 :