Search code examples
pythonpython-3.xpyqt5qpushbuttonqframe

Draw QFrame around QPushButton PyQt5


I am unable to get a QFrame to completely surround a QPushButton Like a Border. It only frames the top and left side of the button. I was wondering what I'm doing wrong with the frame.

import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class main(QWidget):
    def __init__(self):
        super().__init__()
        layout1 = QVBoxLayout()
        btn1 = QPushButton("Test")

        frame = QFrame(btn1)
        frame.setGeometry(btn1.geometry())
        frame.setFrameShape(QFrame.Box)
        frame.setFrameShadow(QFrame.Plain)
        frame.setLineWidth(4)

        layout1.addWidget(btn1)
        self.setLayout(layout1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = main()
    window.show()
    sys.exit(app.exec_())

Solution

  • The problem is caused because the QFrame does not change the size, instead QPushButton does. In my solution I have resized every time the size is changed in the QPushButton

    class FrameButton(QPushButton):
        def __init__(self, *args, **kwargs):
            QPushButton.__init__(self, *args, **kwargs)
            self.frame = QFrame(self)
            self.frame.setFrameShape(QFrame.Box)
            self.frame.setFrameShadow(QFrame.Plain)
            self.frame.setLineWidth(4)
    
        def resizeEvent(self, event):
            self.frame.resize(self.size())
            QWidget.resizeEvent(self, event)
    
    
    class main(QWidget):
        def __init__(self):
            super().__init__()
            layout = QVBoxLayout(self)
            layout.addWidget(FrameButton("Test"))
    

    enter image description here