Как переместить текст внутри значка в QPushButton? - PullRequest
1 голос
/ 01 октября 2019

Я создал пользовательские кнопки PyQt5 со значком SVG. Я должен иметь кликабельные шестиугольники с текстом внутри них. Однако, когда я пытаюсь переместить текст влево, он скрыт шестиугольником.

Я попытался переместить текст влево, используя отступы, но это просто скрывает текст.

HexButton code:

class HexButton(QPushButton):
    def __init__(self, colour, parent=None):
        super(QPushButton, self).__init__(parent)

        # Convert hexagon svg into image
        qimage = QtGui.QImage.fromData(self.svg_hexagon(colour))
        qicon = QtGui.QPixmap(qimage)
        # Set the icon as the hexagon
        self.setIcon(QtGui.QIcon(qicon))
        # Set icon size as the entire thing
        self.setIconSize(QSize(48, 48))
        # Make the button invisible
        self.setStyleSheet("""
        border: none;""")


    def svg_hexagon(self, colour):
        svg_bytes = f'<svg xmlns="http://www.w3.org/2000/svg" width="31" height="31"><path stroke="none" fill="{COLOURS[colour]}" d="M12.5 1.2320508075689a6 6 0 0 1 6 0l7.856406460551 4.5358983848622a6 6 0 0 1 3 5.1961524227066l0 9.0717967697245a6 6 0 0 1 -3 5.1961524227066l-7.856406460551 4.5358983848622a6 6 0 0 1 -6 0l-7.856406460551 -4.5358983848623a6 6 0 0 1 -3 -5.1961524227066l0 -9.0717967697245a6 6 0 0 1 3 -5.1961524227066"></path></svg>'
        return bytearray(svg_bytes, encoding='utf-8')

MainApplication

def main():

    app = QApplication(sys.argv)
    window = QWidget()
    layout = QHBoxLayout(window)

    button = HexButton("blank")
    button.setText("Nice")
    button.move(10, 10)
    layout.addWidget(button)

    window.show()
    sys.exit(app.exec_())

Я ожидаю желтый шестиугольник с текстом внутри.

1 Ответ

0 голосов
/ 01 октября 2019

К сожалению, значок и текст отображаются на одном слое, а значок - после текста, что вызывает указанную вами проблему. Учитывая вышесказанное, возможное решение - создать QLabel над кнопкой:

from PyQt5 import QtCore, QtGui, QtWidgets


class HexButton(QtWidgets.QPushButton):
   def __init__(self, colour, parent=None):
       super(HexButton, self).__init__(parent)

       # Convert hexagon svg into image
       qimage = QtGui.QImage.fromData(self.svg_hexagon(colour))
       qicon = QtGui.QPixmap(qimage)
       # Set the icon as the hexagon
       self.setIcon(QtGui.QIcon(qicon))
       # Set icon size as the entire thing
       self.setIconSize(QtCore.QSize(48, 48))
       # Make the button invisible
       self.setStyleSheet(
           """
       border: none;"""
       )
       self.text_label = QtWidgets.QLabel()
       self.text_label.setContentsMargins(0, 0, 0, 0)
       self.text_label.setStyleSheet("""color : white;""")
       lay = QtWidgets.QVBoxLayout(self)
       lay.addWidget(self.text_label, alignment=QtCore.Qt.AlignCenter)

   def svg_hexagon(self, colour):
       svg_bytes = f'<svg xmlns="http://www.w3.org/2000/svg" width="31" height="31"><path stroke="none" fill="{colour.name()}" d="M12.5 1.2320508075689a6 6 0 0 1 6 0l7.856406460551 4.5358983848622a6 6 0 0 1 3 5.1961524227066l0 9.0717967697245a6 6 0 0 1 -3 5.1961524227066l-7.856406460551 4.5358983848622a6 6 0 0 1 -6 0l-7.856406460551 -4.5358983848623a6 6 0 0 1 -3 -5.1961524227066l0 -9.0717967697245a6 6 0 0 1 3 -5.1961524227066"></path></svg>'
       return bytearray(svg_bytes, encoding="utf-8")

   @property
   def text(self):
       return self.text_label.text()

   @text.setter
   def text(self, t):
       self.text_label.setText(t)


def main():
   import sys

   app = QtWidgets.QApplication(sys.argv)
   window = QtWidgets.QWidget()
   layout = QtWidgets.QHBoxLayout(window)

   button = HexButton(QtGui.QColor("black"))
   button.text = "Nice"
   layout.addWidget(button)

   window.show()
   sys.exit(app.exec_())


if __name__ == "__main__":
   main()

enter image description here

...