我想把QCheckBox的图标从标签的左侧移动到紧挨着右侧。我查看了以下帖子:
以下是我的实验:
- PyQt4 QPushButton text and icon alignment
- Align icon on the right and center the text in a QPushButton
以下是我的实验:
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QCheckBox, QStyle, QApplication, QLabel, QHBoxLayout
class CheckBoxWIcon(QCheckBox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
icon = self.icon()
icon_size = self.iconSize()
# remove icon
self.setIcon(QtGui.QIcon())
label_icon = QLabel()
label_icon.setAttribute(Qt.WA_TranslucentBackground)
label_icon.setAttribute(Qt.WA_TransparentForMouseEvents)
lay = QHBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(label_icon, alignment=Qt.AlignRight)
label_icon.setPixmap(icon.pixmap(icon_size))
app = QApplication([])
mw = QWidget()
layout = QVBoxLayout()
test1 = QCheckBox("Default")
test1.setIcon(app.style().standardIcon(QStyle.SP_MediaSkipForward))
test1.setStyleSheet("""QCheckBox { text-align: right; }""")
test2 = QCheckBox("Using style-sheet")
test2.setIcon(app.style().standardIcon(QStyle.SP_MediaSkipForward))
test2.setStyleSheet("""QCheckBox { text-align: left; }""")
test3 = QCheckBox("Using layout direction")
test3.setIcon(app.style().standardIcon(QStyle.SP_MediaSkipForward))
test3.setLayoutDirection(Qt.RightToLeft)
test4 = CheckBoxWIcon("Custom class", icon=QApplication.style().standardIcon(QStyle.SP_MediaSkipForward))
layout.addWidget(test1)
layout.addWidget(test2)
layout.addWidget(test3)
layout.addWidget(test4)
mw.setLayout(layout)
mw.show()
app.exec()
期望的输出: