3

how to place objects within the confines of a QFrame as i can't get my head around it. I've read the documentation on https://doc.qt.io/qtforpython/PySide2/QtWidgets/QFrame.html but its just not sinking in for me. I've also looked at various code snippets but nothing seems to do what i want.

When i try to call methods of either a QPushButton or QFrame there seems to be no options for either to interact with each other.

from PySide2.QtWidgets import *
import sys

class ButtonTest(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.button1 = QPushButton("Button 1")
        self.button2 = QPushButton("Button 2")

        self.myframe = QFrame()
        self.myframe.setFrameShape(QFrame.StyledPanel)
        self.myframe.setFrameShadow(QFrame.Plain)
        self.myframe.setLineWidth(3)

        self.buttonlayout = QVBoxLayout(self.myframe)
        self.buttonlayout.addWidget(self.button1)
        self.buttonlayout.addWidget(self.button2)

        self.setLayout(self.buttonlayout)


app = QApplication(sys.argv)

mainwindow = ButtonTest()
mainwindow.show()

sys.exit(app.exec_())

They pass in the QFrame as an argument when constructing the layout. This compiles fine, but the frame is nowhere to be seen.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Welshhobo
  • 115
  • 11

1 Answers1

3

The problem is simple: A layout can only be established in a widget, to better understand you have to know that:

lay = QXLayout(foowidet)

equals:

lay = QXLayout()
foowidget.setLayout(lay)

In your code you first pointed out that buttonlayout handles myframe's child widgets(self.buttonlayout = QVBoxLayout(self.myframe)) but then you have set it to handle window's children(self.addWidget(self.myframe).

The solution is to establish the QFrame through a layout:

class ButtonTest(QWidget):
    def __init__(self):
        super(ButtonTest, self).__init__()

        self.button1 = QPushButton("Button 1")
        self.button2 = QPushButton("Button 2")

        self.myframe = QFrame()
        self.myframe.setFrameShape(QFrame.StyledPanel)
        self.myframe.setFrameShadow(QFrame.Plain)
        self.myframe.setLineWidth(3)

        buttonlayout = QVBoxLayout(self.myframe)
        buttonlayout.addWidget(self.button1)
        buttonlayout.addWidget(self.button2)

        lay = QVBoxLayout(self)
        lay.addWidget(self.myframe)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241