有没有办法把QCheckBox的文字放在图标上面?

问题描述 投票:1回答:1

我有一个网格布局,里面有很多复选框。 我想在复选框上添加一个图像以及一些文字。 我遇到的问题是,复选框的布局是从左到右(复选框,图标,文本)。

有没有办法把文字放在图标上面? 不知道使用样式表是否能解决这个问题,甚至不知道那会是什么样子。

谢谢你。

pyqt4 qcheckbox
1个回答
0
投票

答: 在PyQt4中。不,你不能这样做。

为什么? 我读了以下的源代码 QCheckBox Qt4 (C++) 此处此处. 我看到它使用默认 QStyleOptionButton 来显示复选框、文本和图标。它的用途 drawControl 绘制所有元素在 QStyleOptionButton 由指定的配置在 QStyleOptionButton. 也有 LayoutDirection. 而布局方向在 QStyleOptionButton. 我不知道在Qt4 C++和继承它和交换方向图标。但在PyQt4中,这是不可能做到的。

另一种方法? : 是的,它有另一种方法来解决,但不是直接的。你只需要创建你自己的widget,就像 QCheckBox 和禁用图标在 QCheckBox 并自制 QLabel 显示你的图标,并将其设置为相同的。QLayout.

例如:

import sys
from PyQt4 import QtGui, QtCore

class QCustomCheckBox (QtGui.QWidget):
    stateChanged = QtCore.pyqtSignal(int)

    def __init__ (self, text, parentQWidget = None):
        super(QCustomCheckBox, self).__init__(parentQWidget)
        self.customQCheckBox = QtGui.QCheckBox(text)
        self.iconQLabel      = QtGui.QLabel()
        allQHBoxLayout  = QtGui.QHBoxLayout()
        allQHBoxLayout.addWidget(self.customQCheckBox)
        allQHBoxLayout.addWidget(self.iconQLabel)
        allQHBoxLayout.addStretch(1)
        self.setLayout(allQHBoxLayout)
        self.customQCheckBox.stateChanged.connect(self.stateChanged.emit)

    def setPixmap (self, newQPixmap, width = 48, height = 48):
        self.iconQLabel.setPixmap(newQPixmap.scaled(width, height, QtCore.Qt.KeepAspectRatio))

    def pixmap (self):
        return self.iconQLabel.pixmap()

class QCustomWidget (QtGui.QWidget):
    def __init__ (self, parent = None):
        super(QCustomWidget, self).__init__(parent)
        allQVBoxLayout  = QtGui.QVBoxLayout()
        firstQCustomCheckBox = QCustomCheckBox('First Check Box')
        firstQCustomCheckBox.setPixmap(QtGui.QPixmap('1.jpg'))
        allQVBoxLayout.addWidget(firstQCustomCheckBox)
        secondQCustomCheckBox = QCustomCheckBox('Second Check Box')
        secondQCustomCheckBox.setPixmap(QtGui.QPixmap('2.jpg'))
        allQVBoxLayout.addWidget(secondQCustomCheckBox)
        self.setLayout(allQVBoxLayout)

if __name__ == '__main__':
    myQApplication = QtGui.QApplication(sys.argv)
    myQCustomWidget = QCustomWidget()
    myQCustomWidget.show()
    sys.exit(myQApplication.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.