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.

dissidia
  • 1,531
  • 3
  • 23
  • 53
  • 1
    No. Why would you want to do this? – ekhumoro Feb 22 '17 at 01:10
  • 1
    For categorizing and make the ui pretty? – dissidia Feb 22 '17 at 01:14
  • 1
    Why would you **not** want to use a layout? – ekhumoro Feb 22 '17 at 01: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 – dissidia Feb 22 '17 at 01: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. – ekhumoro Feb 22 '17 at 01:45

1 Answers1

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)
Eskimo868
  • 238
  • 1
  • 12