【发布时间】:2020-03-29 19:39:46
【问题描述】:
我正在使用单选按钮来创建垂直标签效果。我已经完成了所有工作,但我一直在做一些我确信很容易的事情。
在这部分代码中,我浏览了一个选项卡名称列表并为每个选项卡生成单选按钮:
def _init_vertical_tabs(self, layout, row):
"""Initialize vertical tabs"""
tabs_widget = QtWidgets.QWidget()
tabs_widget.setObjectName("tabs")
vertical_tabs_layout = QtWidgets.QVBoxLayout()
vertical_tabs_layout.setSpacing(0)
vertical_tabs_layout.setContentsMargins(0, 0, 0, 0)
vertical_tabs_layout.setAlignment(QtCore.Qt.AlignCenter)
tabs_widget.setLayout(vertical_tabs_layout)
layout.addWidget(tabs_widget, row, 0, len(self.tabs), 1)
tabs_widget.setMinimumHeight(self.parent_height)
tabs_widget.setMinimumWidth(self.parent_width*0.15)
tabs_widget.setMaximumHeight(self.parent_height)
tabs_widget.setMaximumWidth(self.parent_width*0.15)
tab_to_widget = dict()
for tab in self.tabs:
tab_button = self._create_tab(tab, vertical_tabs_layout, self.parent_width*0.15, self.parent_height/len(self.tabs),)
tab_to_widget[tab] = tab_button
def _create_tab(self, tab, layout, width, height):
"""Basic method to create a fake tab"""
button = QtWidgets.QRadioButton(tab)
button.setContentsMargins(0, 0, 0, 0)
l = lambda tab_name = tab: self.toggle_visibility_tabs(tab_name)
button.clicked.connect(l)
button.setMinimumHeight(height)
button.setMinimumWidth(width)
button.setMaximumHeight(height)
button.setMaximumWidth(width)
layout.addWidget(button)
然后我应用了一些 css:
QWidget#tabs{
color: #ffffff;
background-color: #005073;
border: 0px solid #e54d42;
text-align: center;
}
QWidget#tabs QRadioButton{
color: #ffffff;
font-weight: 400;
font-size: 20pt;
border-radius: 0px;
background-color: #003850; /*QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #003850, stop:0.5 #005073, stop:1 #003850);*/
margin: 0px;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
QWidget#tabs QRadioButton#Validator{
border-bottom-left-radius: 60px;
border-left: none;
}
QWidget#tabs QRadioButton::indicator{
width: 0px;
height: 0px;
border-radius: 0px;
border: 1px solid #e54d42;
border-top: none;
border-right: none;
border-left: none;
font-family: Arial, Helvetica, sans-serif;
text-align: center;
}
QWidget#tabs QRadioButton:hover, QWidget#tabs QRadioButton:selected, QWidget#tabs QRadioButton:checked{
border-left: 30px solid #e54d42;
color: #e54d42;
}
但这并不是我想要的,首先单选按钮标签仍然是左对齐的,并且由于单选按钮更短,所选按钮的红色边框显然不再位于左侧。有人可以告诉我是否有一种简单的方法可以在 css 或 python 代码中实现这一点?我也尝试了text-align,但也没有用。
谢谢!
【问题讨论】:
-
嗯。我怀疑它只能用样式表来完成。部分解决方案是使用样式表,就像它们不是一样,但不设置文本,这将通过覆盖 paintEvent() 来绘制。
-
您好,感谢您的回复,“部分解决方案是使用样式表,但不设置文本”是什么意思,我不确定这部分。谢谢!
标签: python pyqt pyqt5 qtstylesheets