常用控件5
滚动条
Qt 的控件内部内容如果超过 控件size, 比如, 水平/垂直 layout 里面添加的子控件太多, 溢出部分是不可见的。
如果要看到,就需要滚动条。 这时应该使用 QScrollArea, 如下范例所示
from PySide6.QtWidgets import QApplication, QMainWindow,\
QLabel,QWidget,QVBoxLayout,QScrollArea,QHBoxLayout
# 带滚动条的控件定义
class MyScrollWidget(QScrollArea):
def __init__(self,parent):
super().__init__(parent)
# QScrollArea 修饰的 控件
top_widget = QWidget()
self.setWidget(top_widget)
self.setWidgetResizable(True)
# QScrollArea 修饰控件的 顶层 layout
# 这里 QVBoxLayout 不过是指明 顶层 layout 是 垂直的,
# 并不是说 只会有垂直滚动, 水平方向超过宽度,也可以滚动
top_layout = QVBoxLayout(top_widget)
# hbox水平方向layout,里面增加 40个控件
hbox = QHBoxLayout()
top_layout.addLayout(hbox)
for i in range(40):
hbox .addWidget(QLabel('aaaa'))
# 垂直方向增加 50个控件
for i in range(50):
top_layout .addWidget(QLabel('bbbb'))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# central Widget
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
mainLayout = QVBoxLayout(centralWidget)
mainLayout.addWidget(MyScrollWidget(self))
app = QApplication()
mw = MainWindow()
mw.show()
app.exec()
如果主窗口的所有内容都要处于滚动条内,可以这样写
from PySide6.QtWidgets import QApplication, QMainWindow,\
QLabel,QWidget,QVBoxLayout,QScrollArea,QHBoxLayout
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# QScrollArea 直接作为主窗口的 CentralWidget
scrollArea = QScrollArea(self)
self.setCentralWidget(scrollArea)
# QScrollArea 修饰的 控件
topWidget = QWidget(self)
scrollArea.setWidget(topWidget)
scrollArea.setWidgetResizable(True)
# QScrollArea 修饰控件的 顶层 layout
top_layout = QVBoxLayout(topWidget)
# hbox水平方向layout,里面增加 40个控件
hbox = QHBoxLayout()
top_layout.addLayout(hbox)
for i in range(40):
hbox .addWidget(QLabel('aaaa'))
# 垂直方向增加 50个控件
for i in range(50):
top_layout .addWidget(QLabel('bbbb'))
app = QApplication()
mw = MainWindow()
mw.show()
app.exec()
网络图片Label
QLabel 只能显示本地图片,如果是网络图片需要自己获取
代码如下
from PySide6.QtWidgets import QApplication, QMainWindow,\
QLabel, QWidget,QVBoxLayout
from PySide6 import QtCore,QtGui
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest,QNetworkReply
# 显示网络图片的控件
class ImageLabel(QLabel):
def __init__(self, imgUrl=None, parent=None):
super().__init__(parent)
self.manager = QNetworkAccessManager(self)
self.manager.finished.connect(self.setPixmapFromReply)
if imgUrl is not None:
self.setImageUrl(imgUrl)
def setImageUrl(self, url):
request = QNetworkRequest(QtCore.QUrl(url))
self.manager.get(request)
def setPixmapFromReply(self, reply):
if reply.error() == QNetworkReply.NoError:
pixmap = QtGui.QPixmap()
pixmap.loadFromData(reply.readAll())
self.setPixmap(pixmap)
else:
print("Error loading image:", reply.errorString())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# central Widget
centralWidget = QWidget(self)
self.setCentralWidget(centralWidget)
mainLayout = QVBoxLayout(centralWidget)
img = ImageLabel("https://www.byhy.net/assets/images/favicon.png")
mainLayout.addWidget(img)
app = QApplication()
mw = MainWindow()
mw.show()
app.exec()