Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. PyQt5 - How to change QPushButton QLabel?
Forum Updated to NodeBB v4.3 + New Features

PyQt5 - How to change QPushButton QLabel?

Scheduled Pinned Locked Moved Solved Qt for Python
3 Posts 2 Posters 1.1k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • PatitotectiveP Offline
    PatitotectiveP Offline
    Patitotective
    wrote on last edited by Patitotective
    #1

    I'm trying to outline the text on a QPushButton. I found this to make an outlined label but now i need to set that label as the QPushButton one.

    This code will create an outlined label:

    import sys
    import math
    from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QVBoxLayout
    from PyQt5.QtGui import QPen, QBrush, QFontMetrics, QPainterPath, QPainter
    from PyQt5.QtCore import Qt, QSize
          
    class OutlinedLabel(QLabel):
        
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.w = 1 / 25
            self.mode = True
            self.setBrush(Qt.white)
            self.setPen(Qt.black)
    
        def scaledOutlineMode(self):
            return self.mode
    
        def setScaledOutlineMode(self, state):
            self.mode = state
    
        def outlineThickness(self):
            return self.w * self.font().pointSize() if self.mode else self.w
    
        def setOutlineThickness(self, value):
            self.w = value
    
        def setBrush(self, brush):
            if not isinstance(brush, QBrush):
                brush = QBrush(brush)
            self.brush = brush
    
        def setPen(self, pen):
            if not isinstance(pen, QPen):
                pen = QPen(pen)
            pen.setJoinStyle(Qt.RoundJoin)
            self.pen = pen
    
        def sizeHint(self):
            w = math.ceil(self.outlineThickness() * 2)
            return super().sizeHint() + QSize(w, w)
        
        def minimumSizeHint(self):
            w = math.ceil(self.outlineThickness() * 2)
            return super().minimumSizeHint() + QSize(w, w)
        
        def paintEvent(self, event):
            w = self.outlineThickness()
            rect = self.rect()
            metrics = QFontMetrics(self.font())
            tr = metrics.boundingRect(self.text()).adjusted(0, 0, int(w), int(w)) # DeprecationWarning: an integer is required (got type float).
            if self.indent() == -1:
                if self.frameWidth():
                    indent = (metrics.boundingRect('x').width() + w * 2) / 2
                else:
                    indent = w
            else:
                indent = self.indent()
    
            if self.alignment() & Qt.AlignLeft:
                x = rect.left() + indent - min(metrics.leftBearing(self.text()[0]), 0)
            elif self.alignment() & Qt.AlignRight:
                x = rect.x() + rect.width() - indent - tr.width()
            else:
                x = (rect.width() - tr.width()) / 2
                
            if self.alignment() & Qt.AlignTop:
                y = rect.top() + indent + metrics.ascent()
            elif self.alignment() & Qt.AlignBottom:
                y = rect.y() + rect.height() - indent - metrics.descent()
            else:
                y = (rect.height() + metrics.ascent() - metrics.descent()) / 2
    
            path = QPainterPath()
            path.addText(x, y, self.font(), self.text())
            qp = QPainter(self)
            qp.setRenderHint(QPainter.Antialiasing)
    
            self.pen.setWidthF(w * 2 if w * 2 > 0 else 0) # Otherwise QPen::setWidthF: Setting a pen width with a negative value is not defined
            qp.strokePath(path, self.pen)
            if 1 < self.brush.style() < 15:
                qp.fillPath(path, self.palette().window())
            qp.fillPath(path, self.brush)
    
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.setLayout(QVBoxLayout())
            
            label = OutlinedLabel('Hello world')
            label.setStyleSheet("font-size: 50px;")
            
            self.layout().addWidget(label)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        window = Window()
        window.show()
        
        sys.exit(app.exec_())
    

    Screenshot from 2021-09-19 18-57-25.png

    ndiasN 1 Reply Last reply
    0
    • PatitotectiveP Patitotective

      I'm trying to outline the text on a QPushButton. I found this to make an outlined label but now i need to set that label as the QPushButton one.

      This code will create an outlined label:

      import sys
      import math
      from PyQt5.QtWidgets import QLabel, QWidget, QApplication, QVBoxLayout
      from PyQt5.QtGui import QPen, QBrush, QFontMetrics, QPainterPath, QPainter
      from PyQt5.QtCore import Qt, QSize
            
      class OutlinedLabel(QLabel):
          
          def __init__(self, *args, **kwargs):
              super().__init__(*args, **kwargs)
              self.w = 1 / 25
              self.mode = True
              self.setBrush(Qt.white)
              self.setPen(Qt.black)
      
          def scaledOutlineMode(self):
              return self.mode
      
          def setScaledOutlineMode(self, state):
              self.mode = state
      
          def outlineThickness(self):
              return self.w * self.font().pointSize() if self.mode else self.w
      
          def setOutlineThickness(self, value):
              self.w = value
      
          def setBrush(self, brush):
              if not isinstance(brush, QBrush):
                  brush = QBrush(brush)
              self.brush = brush
      
          def setPen(self, pen):
              if not isinstance(pen, QPen):
                  pen = QPen(pen)
              pen.setJoinStyle(Qt.RoundJoin)
              self.pen = pen
      
          def sizeHint(self):
              w = math.ceil(self.outlineThickness() * 2)
              return super().sizeHint() + QSize(w, w)
          
          def minimumSizeHint(self):
              w = math.ceil(self.outlineThickness() * 2)
              return super().minimumSizeHint() + QSize(w, w)
          
          def paintEvent(self, event):
              w = self.outlineThickness()
              rect = self.rect()
              metrics = QFontMetrics(self.font())
              tr = metrics.boundingRect(self.text()).adjusted(0, 0, int(w), int(w)) # DeprecationWarning: an integer is required (got type float).
              if self.indent() == -1:
                  if self.frameWidth():
                      indent = (metrics.boundingRect('x').width() + w * 2) / 2
                  else:
                      indent = w
              else:
                  indent = self.indent()
      
              if self.alignment() & Qt.AlignLeft:
                  x = rect.left() + indent - min(metrics.leftBearing(self.text()[0]), 0)
              elif self.alignment() & Qt.AlignRight:
                  x = rect.x() + rect.width() - indent - tr.width()
              else:
                  x = (rect.width() - tr.width()) / 2
                  
              if self.alignment() & Qt.AlignTop:
                  y = rect.top() + indent + metrics.ascent()
              elif self.alignment() & Qt.AlignBottom:
                  y = rect.y() + rect.height() - indent - metrics.descent()
              else:
                  y = (rect.height() + metrics.ascent() - metrics.descent()) / 2
      
              path = QPainterPath()
              path.addText(x, y, self.font(), self.text())
              qp = QPainter(self)
              qp.setRenderHint(QPainter.Antialiasing)
      
              self.pen.setWidthF(w * 2 if w * 2 > 0 else 0) # Otherwise QPen::setWidthF: Setting a pen width with a negative value is not defined
              qp.strokePath(path, self.pen)
              if 1 < self.brush.style() < 15:
                  qp.fillPath(path, self.palette().window())
              qp.fillPath(path, self.brush)
      
      class Window(QWidget):
          def __init__(self):
              super().__init__()
              self.setLayout(QVBoxLayout())
              
              label = OutlinedLabel('Hello world')
              label.setStyleSheet("font-size: 50px;")
              
              self.layout().addWidget(label)
      
      if __name__ == '__main__':
          app = QApplication(sys.argv)
          window = Window()
          window.show()
          
          sys.exit(app.exec_())
      

      Screenshot from 2021-09-19 18-57-25.png

      ndiasN Offline
      ndiasN Offline
      ndias
      wrote on last edited by ndias
      #2

      Hi @Patitotective

      You can define a QPushButton as parent widget of OutlinedLabel:

      class Window(QWidget):
          def __init__(self):
              super().__init__()
              self.setLayout(QVBoxLayout())
      
              button = QPushButton()
      
              button = QPushButton(self)
              
              label = OutlinedLabel('Hello world', button)
              label.setStyleSheet("font-size: 50px;")
      
              button.clicked.connect(lambda: print("Button pressed!"))
              button.setFixedSize(label.sizeHint())
              
              self.layout().addWidget(button)
      

      775b9a92-e02e-4912-afb5-caba06e50237-image.png

      PatitotectiveP 1 Reply Last reply
      1
      • ndiasN ndias

        Hi @Patitotective

        You can define a QPushButton as parent widget of OutlinedLabel:

        class Window(QWidget):
            def __init__(self):
                super().__init__()
                self.setLayout(QVBoxLayout())
        
                button = QPushButton()
        
                button = QPushButton(self)
                
                label = OutlinedLabel('Hello world', button)
                label.setStyleSheet("font-size: 50px;")
        
                button.clicked.connect(lambda: print("Button pressed!"))
                button.setFixedSize(label.sizeHint())
                
                self.layout().addWidget(button)
        

        775b9a92-e02e-4912-afb5-caba06e50237-image.png

        PatitotectiveP Offline
        PatitotectiveP Offline
        Patitotective
        wrote on last edited by
        #3

        Thank you @ndias , it worked. 🙃

        1 Reply Last reply
        1

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved