我试图在我的一些小部件中添加一个内部阴影效果:
我已经找到了QGraphicsDropShadowEffect类,但是它似乎不存在于内部阴影中。
我也见过InnerShadow QML型,但我没有使用QML。
实际上,不使用QML就能做到吗?也许用样式表?
发布于 2021-08-28 09:39:55
1.样式表
不幸的是,与此同时,Qt样式表不支持类似css中的“框影”。解决方法之一是使用顶部和左边的渐变边框来模拟效果。
border-left: 20px solid black;
border-top: 20px solid black;
border-left-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
border-top-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
background-color: rgb(240, 240, 240);
下面是一个使用python的例子,但是对于C++用户来说,样式表部分是相同的。
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout
class MainWindow(QWidget):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.resize(600, 400)
self.widget = QWidget()
self.widget.setObjectName("w1")
self.widget2 = QWidget()
self.widget2.setObjectName("w2")
self.widget3 = QWidget()
self.widget3.setObjectName("w3")
self.label = QLabel("20px")
self.label2 = QLabel("10px")
self.label3 = QLabel("3px")
layout = QGridLayout()
layout.addWidget(self.label, 0, 0, alignment=Qt.AlignCenter)
layout.addWidget(self.label2, 0, 1, alignment=Qt.AlignCenter)
layout.addWidget(self.label3, 0, 2, alignment=Qt.AlignCenter)
layout.addWidget(self.widget, 1, 0, 3, 1)
layout.addWidget(self.widget2, 1, 1, 3, 1)
layout.addWidget(self.widget3, 1, 2, 3, 1)
layout.setHorizontalSpacing(20)
self.setLayout(layout)
self.setStyleSheet("""
QWidget{ background-color: rgb(255, 255, 255);}
QLabel {font-size: 20px}
QWidget#w1 {
border-left: 20px solid black;
border-top: 20px solid black;
border-left-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
border-top-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
background-color: rgb(240, 240, 240);
}
QWidget#w2 {
border-left: 10px solid black;
border-top: 10px solid black;
border-left-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
border-top-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
background-color: rgb(240, 240, 240);
}
QWidget#w3 {
border-left: 3px solid black;
border-top: 3px solid black;
border-left-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
border-top-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 rgb(195,195,195), stop: 1 rgb(240, 240, 240));
background-color: rgb(240, 240, 240);
}
""")
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
2. QFrame
另一种创建内部阴影的方法是设置QFrame样式。
就像这样:
QLabel label(...);
label.setFrameStyle(QFrame::Panel | QFrame::Sunken);
label.setLineWidth(2);
label.setMidLineWidth(1);
下面是文档中列出的样式和行宽的一些组合。
https://stackoverflow.com/questions/68941097
复制相似问题