本示例中,演示了QScrollArea的使用,以及QScrollBar的样式设定,在代码中使用setStyleSheet设置样式,记得要优先设置scrollArea,再设置窗口的样式,不然QScrollBar的样式会不起作用,使用QSS设置没有这个要求。
效果图:
源代码:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QScrollArea
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(644, 488)
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.scrollArea = QtWidgets.QScrollArea(Form)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 624, 468))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.pushButton = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
self.pushButton.setObjectName("pushButton")
self.verticalLayout_2.addWidget(self.pushButton)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout.addWidget(self.scrollArea)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "PushButton"))
class DEMO(QDialog, Ui_Form):
def __init__(self):
super(DEMO, self).__init__()
self.setupUi(self)
self.resize(955, 625)
for x in range(30):
self.scrollAreaWidgetContents.layout().addWidget(QPushButton(f'Button{x}'))
self.scrollAreaWidgetContents.layout().setContentsMargins(2, 2, 2, 2)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setStyleSheet("""
QScrollBar:vertical {
border: none;
background: #E2E2E2;
width: 15px;
margin: 10px 0;
}
QScrollBar::handle:vertical {
background: blue;
min-height: 20px;
}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical
{
width: 0px;
height: 0px;
}
""")
self.setStyleSheet("""
#scrollArea {
border: none;
border-radius: 6px;
padding: 4px;
background-color: #ffffff;
}
#scrollAreaWidgetContents{
background-color: rgb(255,255,255,0);
}
""")
if __name__ == '__main__':
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
app = QApplication(sys.argv)
main_win = DEMO()
main_win.show()
sys.exit(app.exec_())