【问题标题】:Is there a way to put the text of a QCheckBox above the icon?有没有办法将 QCheckBox 的文本放在图标上方?
【发布时间】:2023-12-11 00:27:01
【问题描述】:

我有一个包含一堆复选框的网格布局。我想在复选框中添加图像以及一些文本。我遇到的问题是复选框的布局是从左到右(复选框、图标、文本)。

有没有办法将文字放在图标上方?不确定使用样式表是否适用于此,甚至不知道它的外观。

谢谢。

【问题讨论】:

    标签: pyqt4 qcheckbox


    【解决方案1】:

    答案: 在 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_())
    

    【讨论】:

      最近更新 更多