6

I am trying to add a QPushButton widget into a QGroupBox such as:

self.btn = QtGui.QPushButton('Push Button')
self.grp_box = QtGui.QGroupBox('Button Section')
self.grp_box.addWidget(self.btn)

When trying to run the code, I got this error : AttributeError: 'NoneType' object has no attribute 'addWidget'

After some online checking, it seems that QGroupBox only allows setLayout, meaning I will need to use QVBoxLayout or QHBoxLayout etc.

Is there anyway to get around this, adding in a widget without the use of any layout(s)? I am using PyQt.

5
  • 1
    No. Why would you want to do this? Commented Feb 22, 2017 at 1:10
  • 1
    For categorizing and make the ui pretty? Commented Feb 22, 2017 at 1:14
  • 1
    Why would you not want to use a layout? Commented Feb 22, 2017 at 1:17
  • I am not sure if this can be done without the use of layout. Also, say if I only have a pushbutton, I am not seeing the point that I need to add this button into a layout then onto a groupBox (this is just me saying..) and hence I am asking Commented Feb 22, 2017 at 1:24
  • 1
    Make the button a child of the group-box. It should then appear by default in the top-left corner of the group-box - but will probably obscure its title. So then you will need to give the button an absolute position (e.g. button.move(20, 20)). However, if the group-box changes size, it could also obscure the button, so you will need to set a minimum size for the group-box, etc, etc. Of course, the whole point of layouts is to avoid having to deal with all these tedious details and allow Qt to manage it all automatically. Commented Feb 22, 2017 at 1:45

1 Answer 1

3

First create your main layout = QHBoxLayout()

  main_layout = QHBoxLayout()

Then create the group box:

  group_box = QGroupBox("Group Box")

Create the group box layout:

  group_box_layout = QVBoxLayout()

Add widgets to the group box layout like this:

  group_box_layout.addWidget(QCheckBox("Check Box 1"))
  group_box_layout.addWidget(QCheckBox("Check Box 2"))
  group_box_layout.addWidget(QCheckBox("Check Box 3"))

Assign the group box layout to the group box:

  group_box.setLayout(group_box_layout)

Assing the group box to the main layout:

  main_layout.addWidget(group_box)

And add this at the end:

    widget = QWidget()
    widget.setLayout(layout1)
    self.setCentralWidget(widget)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.