当前,单选按钮小部件的格式是:
我想完全消除文本,并将指示器居中在小部件内。这样看起来像这样:
我需要做什么来格式化窗口小部件?我正在使用编辑器,但是我的代码中的某些部分是手写的,所以我希望答案在两者之间起作用。谢谢!
您必须使用QProxyStyle来移动QRadioButton指示器的位置:
import sys
from PyQt5 import QtCore, QtWidgets
class ProxyStyle(QtWidgets.QProxyStyle):
def subElementRect(self, element, option, widget):
r = super().subElementRect(element, option, widget)
if element in (
QtWidgets.QStyle.SE_RadioButtonIndicator,
QtWidgets.QStyle.SE_RadioButtonFocusRect,
QtWidgets.QStyle.SE_RadioButtonClickRect,
):
r.moveCenter(option.rect.center())
return r
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle(ProxyStyle())
w = QtWidgets.QWidget()
lay = QtWidgets.QHBoxLayout(w)
for _ in range(3):
btn = QtWidgets.QRadioButton()
btn.setStyleSheet("background-color: palette(button);")
btn.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
lay.addWidget(btn)
w.resize(320, 240)
w.show()
sys.exit(app.exec_())
更新:
此更改在Qt Designer中无法观察到,因此您必须使用代码,例如:
├── main.py
└── mainwindow.ui
mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QRadioButton" name="radioButton">
<property name="geometry">
<rect>
<x>130</x>
<y>120</y>
<width>221</width>
<height>221</height>
</rect>
</property>
<property name="styleSheet">
<string notr="true">background-color: rgb(252, 233, 79);</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>24</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
main.py
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class ProxyStyle(QtWidgets.QProxyStyle):
def subElementRect(self, element, option, widget):
r = super().subElementRect(element, option, widget)
if element in (
QtWidgets.QStyle.SE_RadioButtonIndicator,
QtWidgets.QStyle.SE_RadioButtonFocusRect,
QtWidgets.QStyle.SE_RadioButtonClickRect,
):
r.moveCenter(option.rect.center())
return r
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle(ProxyStyle())
w = uic.loadUi(os.path.join(CURRENT_DIR, "mainwindow.ui"))
w.show()
sys.exit(app.exec_())
输出:
注:我为QRadioButton添加了背景色,以便可以区分位置。