有没有办法将QCheckBox的文本放在图标上方?

时间:2014-09-04 19:49:21

标签: pyqt4 qcheckbox

我有一个gridlayout,它包含一堆复选框。我想在复选框和一些文本中添加图像。我遇到的问题是复选框的布局是从左到右(复选框,图标,文本)。

有没有办法将文字放在图标上方?不确定使用样式表是否适用于此,或者甚至不会如此。

谢谢。

1 个答案:

答案 0 :(得分:0)

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

为什么?我阅读了QCheckBox Qt4(C ++)herehere的源代码。我看到它使用默认QStyleOptionButton来显示复选框,文本和图标。它使用drawControl通过QStyleOptionButton中的指定配置在QStyleOptionButton中绘制所有元素。它还有LayoutDirection。和QStyleOptionButton中的布局方向。我不会在Qt4 C ++中知道并继承它并交换方向图标。但在PyQt4中,它是不可能的。

另一种方式?:是的,它有另一种方法可以解决而不是直接解决。您只需创建自己的小部件,就像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_())
相关问题