QGridlayout and QGroupbox alignment - python

I've created a widget with contents of 3 QGroupbox, I am trying to place and align them respectively with QGridLayout. Strange behaviour of QGroupboxsmakes this question.
What looks like currently.
As shown above figure when Qwidget screen stretchs in and out, Every group overlap each other and by outstretching replaces strangely and unwanted.
What I want to be....
By stretching in want all groups keeping its own position Fixed and scrollbar would appear instead.
The code is:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class ClassWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassWidget, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 670, 360))
self.A = ClassA()
self.B = ClassB()
self.C = ClassC()
grid = QtWidgets.QGridLayout(self)
grid.addWidget(self.A, 0, 0)
grid.addWidget(self.B, 0, 1, 1, 2)
grid.addWidget(self.C, 1, 0, 1, 2)
class ClassA(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassA, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.c_lay = QtWidgets.QHBoxLayout()
fctd = "One\n\nTwo\n\nThree"
con_strength = QtWidgets.QLabel(fctd)
self.value = QtWidgets.QLineEdit('Test')
self.c_lay.addWidget(con_strength)
self.c_lay.addWidget(self.value, alignment=QtCore.Qt.AlignRight)
self.combo = QtWidgets.QComboBox()
self.combo.addItems(["10","12","14","16"])
self.hbox = QtWidgets.QHBoxLayout()
self.con = QtWidgets.QLabel("Number: ")
self.hbox.addWidget(self.con)
self.hbox.addWidget(self.combo)
self.vlay = QtWidgets.QVBoxLayout()
self.vlay.addLayout(self.hbox)
self.vlay.addLayout(self.c_lay)
self.vlay.addStretch()
Concrete_Group = QtWidgets.QGroupBox(self)
Concrete_Group.setTitle("&GroupA")
Concrete_Group.setLayout(self.vlay)
self.comth = ["10","12","14","16"]
self.combo.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
value = self.comth[index]
self.display_data(value)
def display_data(self, value):
try:
f = value
f_value = "{}"
self.value.setText(f_value.format(f))
except ValueError:
print("Error")
class ClassB(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassB, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.combo_exclass = QtWidgets.QComboBox()
self.combo_exclass.addItems([" Very dry area"," Dry or permanently
wet"," Wet, rarely dry"," Moderate humidity"," Tidal splash & spray
zones"])
self.combo_lclass = QtWidgets.QComboBox()
self.combo_lclass.addItems(["L2","L4","L6","L8"])
self.combo_vct = QtWidgets.QComboBox()
self.combo_vct.addItems(["0.10","0.20","0.30","0.40",
"0.50","0.60","0.70"])
self.combo_in = QtWidgets.QComboBox()
self.combo_in.addItems(["Class1","Class2","Class3"])
self.tbox = QtWidgets.QHBoxLayout()
self.exclass = QtWidgets.QLabel("Class1: ")
self.tbox.addWidget(self.exclass)
self.tbox.addWidget(self.combo_exclass)
self.mtbox = QtWidgets.QHBoxLayout()
self.lclass = QtWidgets.QLabel("Class2: ")
self.mtbox.addWidget(self.lclass)
self.mtbox.addWidget(self.combo_lclass)
self.mbbox = QtWidgets.QHBoxLayout()
self.vct = QtWidgets.QLabel("Class3: ")
self.mbbox.addWidget(self.vct)
self.mbbox.addWidget(self.combo_vct)
self.bbox = QtWidgets.QHBoxLayout()
self.inl = QtWidgets.QLabel("Class4: ")
self.bbox.addWidget(self.inl)
self.bbox.addWidget(self.combo_in)
self.grid = QtWidgets.QGridLayout()
self.grid.addLayout(self.tbox, 0, 0, 1, 2)
self.grid.addLayout(self.mtbox, 1, 0)
self.grid.addLayout(self.mbbox, 2, 0)
self.grid.addLayout(self.bbox, 3, 0)
Environment_Group = QtWidgets.QGroupBox(self)
Environment_Group.setTitle("&Group2")
Environment_Group.setLayout(self.grid)
class ClassC(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassC, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.topone = QtWidgets.QComboBox()
self.topone.addItems(["One","Two","Three","four"])
self.longitudinalone = QtWidgets.QComboBox()
self.longitudinalone.addItems(["One","Two","Three","four"])
self.bottomone = QtWidgets.QComboBox()
self.bottomone.addItems(["One","Two","Three","four"])
self.stirrupone = QtWidgets.QComboBox()
self.stirrupone.addItems(["One","Two","Three","four"])
self.toprebar = QtWidgets.QComboBox()
self.toprebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.longitudinalrebar = QtWidgets.QComboBox()
self.longitudinalrebar.addItems(["1","2","3","4","5","6",
"7","8","9"])
self.bottomrebar = QtWidgets.QComboBox()
self.bottomrebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.stirruprebar = QtWidgets.QComboBox()
self.stirruprebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.rebarbox = QtWidgets.QVBoxLayout()
self.topvoid = QtWidgets.QLabel(" ")
self.top = QtWidgets.QLabel("One: ")
self.longitudinal = QtWidgets.QLabel("Two: ")
self.bottom = QtWidgets.QLabel("Three: ")
self.stirrup = QtWidgets.QLabel("Four: ")
self.rebarbox.addWidget(self.topvoid)
self.rebarbox.addWidget(self.top)
self.rebarbox.addWidget(self.longitudinal)
self.rebarbox.addWidget(self.bottom)
self.rebarbox.addWidget(self.stirrup)
self.typebox = QtWidgets.QVBoxLayout()
self.type = QtWidgets.QLabel("Type ")
self.typebox.addWidget(self.type, alignment=QtCore.Qt.AlignCenter)
self.typebox.addWidget(self.topone)
self.typebox.addWidget(self.longitudinalone)
self.typebox.addWidget(self.bottomone)
self.typebox.addWidget(self.stirrupone)
self.Reinforcebox = QtWidgets.QVBoxLayout()
self.Reinforcement = QtWidgets.QLabel("One, One")
self.Reinforcebox.addWidget(self.Reinforcement)
self.Reinforcebox.addWidget(self.toprebar)
self.Reinforcebox.addWidget(self.longitudinalrebar)
self.Reinforcebox.addWidget(self.bottomrebar)
self.Reinforcebox.addWidget(self.stirruprebar)
self.designstrengthbox = QtWidgets.QVBoxLayout()
self.designsteelstrength = QtWidgets.QLabel("Four")
self.topsteelstrength = QtWidgets.QLabel("")
self.longsteelstrength = QtWidgets.QLabel("")
self.bottompsteelstrength = QtWidgets.QLabel("")
self.stirrupsteelstrength = QtWidgets.QLabel("")
self.designstrengthbox.addWidget(self.designsteelstrength)
self.designstrengthbox.addWidget(self.topsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.longsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.bottompsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.stirrupsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.sbox = QtWidgets.QVBoxLayout()
self.anytext = QtWidgets.QLabel("Any text")
self.value = QtWidgets.QLabel("Any")
self.value1 = QtWidgets.QLabel("Any")
self.value2 = QtWidgets.QLabel("Any")
self.value3 = QtWidgets.QLabel("Any")
self.sbox.addWidget(self.anytext)
self.sbox.addWidget(self.value)
self.sbox.addWidget(self.value1)
self.sbox.addWidget(self.value2)
self.sbox.addWidget(self.value3)
self.hlay = QtWidgets.QHBoxLayout()
self.hlay.addStretch()
self.hlay.addLayout(self.rebarbox)
self.hlay.addLayout(self.typebox)
self.hlay.addLayout(self.Reinforcebox)
self.hlay.addLayout(self.designstrengthbox)
self.hlay.addLayout(self.sbox)
self.hlay.addStretch()
Concrete_Group = QtWidgets.QGroupBox(self)
Concrete_Group.setTitle("&GroupC")
Concrete_Group.setLayout(self.hlay)
self.rebarstrength = ["1","2","3","4"]
self.topone.activated.connect(self.setdatatopstrength)
#QtCore.pyqtSlot(int)
def setdatatopstrength(self, index):
value = self.rebarstrength[index]
self.display_topsteeldata(value)
#QtCore.pyqtSlot(int)
def display_topsteeldata(self, value):
try:
gammas = 1.15
fyd = int(float(value)/gammas)
fmt = "{}"
self.topsteelstrength.setText(fmt.format(str(fyd)))
except ValueError:
print("Error")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = ClassWidget()
w.show()
sys.exit(app.exec_())

The problem is simple, the groupboxes that are inside ClassA, ClassB and ClassC are just children and therefore the minimunSizeHint() of ClassA, ClassB and ClassC is (0, 0). For example, we show classA:
So there are 2 solutions:
1. The first is to establish a layout for ClassA, ClassB and ClassC classes, for example:
...
Concrete_Group = QtWidgets.QGroupBox()
Concrete_Group.setTitle("&GroupA")
Concrete_Group.setLayout(self.vlay)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(Concrete_Group)
...
Complete code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class ClassWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassWidget, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 670, 360))
self.A = ClassA()
self.B = ClassB()
self.C = ClassC()
grid = QtWidgets.QGridLayout(self)
grid.addWidget(self.A, 0, 0)
grid.addWidget(self.B, 0, 1, 1, 2)
grid.addWidget(self.C, 1, 0, 1, 2)
class ClassA(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassA, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.c_lay = QtWidgets.QHBoxLayout()
fctd = "One\n\nTwo\n\nThree"
con_strength = QtWidgets.QLabel(fctd)
self.value = QtWidgets.QLineEdit('Test')
self.c_lay.addWidget(con_strength)
self.c_lay.addWidget(self.value, alignment=QtCore.Qt.AlignRight)
self.combo = QtWidgets.QComboBox()
self.combo.addItems(["10","12","14","16"])
self.hbox = QtWidgets.QHBoxLayout()
self.con = QtWidgets.QLabel("Number: ")
self.hbox.addWidget(self.con)
self.hbox.addWidget(self.combo)
self.vlay = QtWidgets.QVBoxLayout()
self.vlay.addLayout(self.hbox)
self.vlay.addLayout(self.c_lay)
self.vlay.addStretch()
Concrete_Group = QtWidgets.QGroupBox()
Concrete_Group.setTitle("&GroupA")
Concrete_Group.setLayout(self.vlay)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(Concrete_Group)
self.comth = ["10","12","14","16"]
self.combo.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
value = self.comth[index]
self.display_data(value)
def display_data(self, value):
try:
f = value
f_value = "{}"
self.value.setText(f_value.format(f))
except ValueError:
print("Error")
class ClassB(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassB, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.combo_exclass = QtWidgets.QComboBox()
self.combo_exclass.addItems([" Very dry area"," Dry or permanently wet"," Wet, rarely dry"," Moderate humidity"," Tidal splash & spray zones"])
self.combo_lclass = QtWidgets.QComboBox()
self.combo_lclass.addItems(["L2","L4","L6","L8"])
self.combo_vct = QtWidgets.QComboBox()
self.combo_vct.addItems(["0.10","0.20","0.30","0.40",
"0.50","0.60","0.70"])
self.combo_in = QtWidgets.QComboBox()
self.combo_in.addItems(["Class1","Class2","Class3"])
self.tbox = QtWidgets.QHBoxLayout()
self.exclass = QtWidgets.QLabel("Class1: ")
self.tbox.addWidget(self.exclass)
self.tbox.addWidget(self.combo_exclass)
self.mtbox = QtWidgets.QHBoxLayout()
self.lclass = QtWidgets.QLabel("Class2: ")
self.mtbox.addWidget(self.lclass)
self.mtbox.addWidget(self.combo_lclass)
self.mbbox = QtWidgets.QHBoxLayout()
self.vct = QtWidgets.QLabel("Class3: ")
self.mbbox.addWidget(self.vct)
self.mbbox.addWidget(self.combo_vct)
self.bbox = QtWidgets.QHBoxLayout()
self.inl = QtWidgets.QLabel("Class4: ")
self.bbox.addWidget(self.inl)
self.bbox.addWidget(self.combo_in)
self.grid = QtWidgets.QGridLayout()
self.grid.addLayout(self.tbox, 0, 0, 1, 2)
self.grid.addLayout(self.mtbox, 1, 0)
self.grid.addLayout(self.mbbox, 2, 0)
self.grid.addLayout(self.bbox, 3, 0)
Environment_Group = QtWidgets.QGroupBox()
Environment_Group.setTitle("&Group2")
Environment_Group.setLayout(self.grid)
vlay = QtWidgets.QVBoxLayout(self)
vlay.addWidget(Environment_Group)
class ClassC(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassC, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.topone = QtWidgets.QComboBox()
self.topone.addItems(["One","Two","Three","four"])
self.longitudinalone = QtWidgets.QComboBox()
self.longitudinalone.addItems(["One","Two","Three","four"])
self.bottomone = QtWidgets.QComboBox()
self.bottomone.addItems(["One","Two","Three","four"])
self.stirrupone = QtWidgets.QComboBox()
self.stirrupone.addItems(["One","Two","Three","four"])
self.toprebar = QtWidgets.QComboBox()
self.toprebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.longitudinalrebar = QtWidgets.QComboBox()
self.longitudinalrebar.addItems(["1","2","3","4","5","6",
"7","8","9"])
self.bottomrebar = QtWidgets.QComboBox()
self.bottomrebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.stirruprebar = QtWidgets.QComboBox()
self.stirruprebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.rebarbox = QtWidgets.QVBoxLayout()
self.topvoid = QtWidgets.QLabel(" ")
self.top = QtWidgets.QLabel("One: ")
self.longitudinal = QtWidgets.QLabel("Two: ")
self.bottom = QtWidgets.QLabel("Three: ")
self.stirrup = QtWidgets.QLabel("Four: ")
self.rebarbox.addWidget(self.topvoid)
self.rebarbox.addWidget(self.top)
self.rebarbox.addWidget(self.longitudinal)
self.rebarbox.addWidget(self.bottom)
self.rebarbox.addWidget(self.stirrup)
self.typebox = QtWidgets.QVBoxLayout()
self.type = QtWidgets.QLabel("Type ")
self.typebox.addWidget(self.type, alignment=QtCore.Qt.AlignCenter)
self.typebox.addWidget(self.topone)
self.typebox.addWidget(self.longitudinalone)
self.typebox.addWidget(self.bottomone)
self.typebox.addWidget(self.stirrupone)
self.Reinforcebox = QtWidgets.QVBoxLayout()
self.Reinforcement = QtWidgets.QLabel("One, One")
self.Reinforcebox.addWidget(self.Reinforcement)
self.Reinforcebox.addWidget(self.toprebar)
self.Reinforcebox.addWidget(self.longitudinalrebar)
self.Reinforcebox.addWidget(self.bottomrebar)
self.Reinforcebox.addWidget(self.stirruprebar)
self.designstrengthbox = QtWidgets.QVBoxLayout()
self.designsteelstrength = QtWidgets.QLabel("Four")
self.topsteelstrength = QtWidgets.QLabel()
self.longsteelstrength = QtWidgets.QLabel()
self.bottompsteelstrength = QtWidgets.QLabel()
self.stirrupsteelstrength = QtWidgets.QLabel()
self.designstrengthbox.addWidget(self.designsteelstrength)
self.designstrengthbox.addWidget(self.topsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.longsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.bottompsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.stirrupsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.sbox = QtWidgets.QVBoxLayout()
self.anytext = QtWidgets.QLabel("Any text")
self.value = QtWidgets.QLabel("Any")
self.value1 = QtWidgets.QLabel("Any")
self.value2 = QtWidgets.QLabel("Any")
self.value3 = QtWidgets.QLabel("Any")
self.sbox.addWidget(self.anytext)
self.sbox.addWidget(self.value)
self.sbox.addWidget(self.value1)
self.sbox.addWidget(self.value2)
self.sbox.addWidget(self.value3)
self.hlay = QtWidgets.QHBoxLayout()
self.hlay.addStretch()
self.hlay.addLayout(self.rebarbox)
self.hlay.addLayout(self.typebox)
self.hlay.addLayout(self.Reinforcebox)
self.hlay.addLayout(self.designstrengthbox)
self.hlay.addLayout(self.sbox)
self.hlay.addStretch()
Concrete_Group = QtWidgets.QGroupBox()
Concrete_Group.setTitle("&GroupC")
Concrete_Group.setLayout(self.hlay)
self.rebarstrength = ["1","2","3","4"]
self.topone.activated.connect(self.setdatatopstrength)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(Concrete_Group)
#QtCore.pyqtSlot(int)
def setdatatopstrength(self, index):
value = self.rebarstrength[index]
self.display_topsteeldata(value)
#QtCore.pyqtSlot(int)
def display_topsteeldata(self, value):
try:
gammas = 1.15
fyd = int(float(value)/gammas)
fmt = "{}"
self.topsteelstrength.setText(fmt.format(str(fyd)))
except ValueError:
print("Error")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = ClassWidget()
w.show()
sys.exit(app.exec_())
2. Or classA, class and class are inherited from QGroubBox, for this you can, for example, do the following:
class ClassA(QtWidgets.QGroupBox):
def __init__(self, parent=None):
super(ClassA, self).__init__(parent)
...
self.setTitle("&GroupA")
self.setLayout(self.vlay)
...
Complete code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class ClassWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ClassWidget, self).__init__(parent)
self.setGeometry(QtCore.QRect(200, 100, 670, 360))
self.A = ClassA()
self.B = ClassB()
self.C = ClassC()
grid = QtWidgets.QGridLayout(self)
grid.addWidget(self.A, 0, 0)
grid.addWidget(self.B, 0, 1, 1, 2)
grid.addWidget(self.C, 1, 0, 1, 2)
class ClassA(QtWidgets.QGroupBox):
def __init__(self, parent=None):
super(ClassA, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.c_lay = QtWidgets.QHBoxLayout()
fctd = "One\n\nTwo\n\nThree"
con_strength = QtWidgets.QLabel(fctd)
self.value = QtWidgets.QLineEdit('Test')
self.c_lay.addWidget(con_strength)
self.c_lay.addWidget(self.value, alignment=QtCore.Qt.AlignRight)
self.combo = QtWidgets.QComboBox()
self.combo.addItems(["10","12","14","16"])
self.hbox = QtWidgets.QHBoxLayout()
self.con = QtWidgets.QLabel("Number: ")
self.hbox.addWidget(self.con)
self.hbox.addWidget(self.combo)
self.vlay = QtWidgets.QVBoxLayout()
self.vlay.addLayout(self.hbox)
self.vlay.addLayout(self.c_lay)
self.vlay.addStretch()
self.setTitle("&GroupA")
self.setLayout(self.vlay)
self.comth = ["10","12","14","16"]
self.combo.activated.connect(self.setdatastrength)
#QtCore.pyqtSlot(int)
def setdatastrength(self, index):
value = self.comth[index]
self.display_data(value)
def display_data(self, value):
try:
f = value
f_value = "{}"
self.value.setText(f_value.format(f))
except ValueError:
print("Error")
class ClassB(QtWidgets.QGroupBox):
def __init__(self, parent=None):
super(ClassB, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.combo_exclass = QtWidgets.QComboBox()
self.combo_exclass.addItems([" Very dry area"," Dry or permanently wet"," Wet, rarely dry"," Moderate humidity"," Tidal splash & spray zones"])
self.combo_lclass = QtWidgets.QComboBox()
self.combo_lclass.addItems(["L2","L4","L6","L8"])
self.combo_vct = QtWidgets.QComboBox()
self.combo_vct.addItems(["0.10","0.20","0.30","0.40",
"0.50","0.60","0.70"])
self.combo_in = QtWidgets.QComboBox()
self.combo_in.addItems(["Class1","Class2","Class3"])
self.tbox = QtWidgets.QHBoxLayout()
self.exclass = QtWidgets.QLabel("Class1: ")
self.tbox.addWidget(self.exclass)
self.tbox.addWidget(self.combo_exclass)
self.mtbox = QtWidgets.QHBoxLayout()
self.lclass = QtWidgets.QLabel("Class2: ")
self.mtbox.addWidget(self.lclass)
self.mtbox.addWidget(self.combo_lclass)
self.mbbox = QtWidgets.QHBoxLayout()
self.vct = QtWidgets.QLabel("Class3: ")
self.mbbox.addWidget(self.vct)
self.mbbox.addWidget(self.combo_vct)
self.bbox = QtWidgets.QHBoxLayout()
self.inl = QtWidgets.QLabel("Class4: ")
self.bbox.addWidget(self.inl)
self.bbox.addWidget(self.combo_in)
self.grid = QtWidgets.QGridLayout()
self.grid.addLayout(self.tbox, 0, 0, 1, 2)
self.grid.addLayout(self.mtbox, 1, 0)
self.grid.addLayout(self.mbbox, 2, 0)
self.grid.addLayout(self.bbox, 3, 0)
self.setTitle("&Group2")
self.setLayout(self.grid)
class ClassC(QtWidgets.QGroupBox):
def __init__(self, parent=None):
super(ClassC, self).__init__(parent)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
self.topone = QtWidgets.QComboBox()
self.topone.addItems(["One","Two","Three","four"])
self.longitudinalone = QtWidgets.QComboBox()
self.longitudinalone.addItems(["One","Two","Three","four"])
self.bottomone = QtWidgets.QComboBox()
self.bottomone.addItems(["One","Two","Three","four"])
self.stirrupone = QtWidgets.QComboBox()
self.stirrupone.addItems(["One","Two","Three","four"])
self.toprebar = QtWidgets.QComboBox()
self.toprebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.longitudinalrebar = QtWidgets.QComboBox()
self.longitudinalrebar.addItems(["1","2","3","4","5","6",
"7","8","9"])
self.bottomrebar = QtWidgets.QComboBox()
self.bottomrebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.stirruprebar = QtWidgets.QComboBox()
self.stirruprebar.addItems(["1","2","3","4","5","6","7","8","9"])
self.rebarbox = QtWidgets.QVBoxLayout()
self.topvoid = QtWidgets.QLabel(" ")
self.top = QtWidgets.QLabel("One: ")
self.longitudinal = QtWidgets.QLabel("Two: ")
self.bottom = QtWidgets.QLabel("Three: ")
self.stirrup = QtWidgets.QLabel("Four: ")
self.rebarbox.addWidget(self.topvoid)
self.rebarbox.addWidget(self.top)
self.rebarbox.addWidget(self.longitudinal)
self.rebarbox.addWidget(self.bottom)
self.rebarbox.addWidget(self.stirrup)
self.typebox = QtWidgets.QVBoxLayout()
self.type = QtWidgets.QLabel("Type ")
self.typebox.addWidget(self.type, alignment=QtCore.Qt.AlignCenter)
self.typebox.addWidget(self.topone)
self.typebox.addWidget(self.longitudinalone)
self.typebox.addWidget(self.bottomone)
self.typebox.addWidget(self.stirrupone)
self.Reinforcebox = QtWidgets.QVBoxLayout()
self.Reinforcement = QtWidgets.QLabel("One, One")
self.Reinforcebox.addWidget(self.Reinforcement)
self.Reinforcebox.addWidget(self.toprebar)
self.Reinforcebox.addWidget(self.longitudinalrebar)
self.Reinforcebox.addWidget(self.bottomrebar)
self.Reinforcebox.addWidget(self.stirruprebar)
self.designstrengthbox = QtWidgets.QVBoxLayout()
self.designsteelstrength = QtWidgets.QLabel("Four")
self.topsteelstrength = QtWidgets.QLabel()
self.longsteelstrength = QtWidgets.QLabel()
self.bottompsteelstrength = QtWidgets.QLabel()
self.stirrupsteelstrength = QtWidgets.QLabel()
self.designstrengthbox.addWidget(self.designsteelstrength)
self.designstrengthbox.addWidget(self.topsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.longsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.bottompsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.designstrengthbox.addWidget(self.stirrupsteelstrength, alignment=QtCore.Qt.AlignCenter)
self.sbox = QtWidgets.QVBoxLayout()
self.anytext = QtWidgets.QLabel("Any text")
self.value = QtWidgets.QLabel("Any")
self.value1 = QtWidgets.QLabel("Any")
self.value2 = QtWidgets.QLabel("Any")
self.value3 = QtWidgets.QLabel("Any")
self.sbox.addWidget(self.anytext)
self.sbox.addWidget(self.value)
self.sbox.addWidget(self.value1)
self.sbox.addWidget(self.value2)
self.sbox.addWidget(self.value3)
self.hlay = QtWidgets.QHBoxLayout()
self.hlay.addStretch()
self.hlay.addLayout(self.rebarbox)
self.hlay.addLayout(self.typebox)
self.hlay.addLayout(self.Reinforcebox)
self.hlay.addLayout(self.designstrengthbox)
self.hlay.addLayout(self.sbox)
self.hlay.addStretch()
self.setTitle("&GroupC")
self.setLayout(self.hlay)
self.rebarstrength = ["1","2","3","4"]
self.topone.activated.connect(self.setdatatopstrength)
#QtCore.pyqtSlot(int)
def setdatatopstrength(self, index):
value = self.rebarstrength[index]
self.display_topsteeldata(value)
#QtCore.pyqtSlot(int)
def display_topsteeldata(self, value):
try:
gammas = 1.15
fyd = int(float(value)/gammas)
fmt = "{}"
self.topsteelstrength.setText(fmt.format(str(fyd)))
except ValueError:
print("Error")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = ClassWidget()
w.show()
sys.exit(app.exec_())

Related

PyQt5 Different Grids on Different Tabs

I am trying to design a GUI interface that will have two Tabs both Tabs have there own Grid. However, I am getting this GUI Look;
Here is my code:
class Ui_MainWindow(QMainWindow):
def __init__(self):
super(Ui_MainWindow, self).__init__()
self.setupUi()
def generate_pstest_tab_elements(self,str1):
groupBox = QGroupBox(str1)
label1 = QLabel(self)
label1.setText('Serial No:')
line1 = QLineEdit(self)
line1.setText("XXXX")
label2 = QLabel(self)
label2.setText('Chip ID:')
line2 = QLineEdit(self)
line2.setText("XXXX")
rd_group = QButtonGroup()
rdbtn_FCB15 = QRadioButton("FCB-15")
rdbtn_DCB15 = QRadioButton("DCB-15")
rd_group.addButton(rdbtn_FCB15)
rd_group.addButton(rdbtn_FCB15)
layout1 = QFormLayout()
layout1.addRow(label1,line1)
layout1.addRow(label2,line2)
layout1.addRow(rdbtn_FCB15,rdbtn_DCB15)
grid1 = QGridLayout()
grid1.addWidget(label1,0,0)
grid1.addWidget(line1,0,1)
grid1.addWidget(rdbtn_FCB15,0,2)
grid1.addWidget(rdbtn_DCB15,0,3)
grid1.addWidget(label2,1,0)
grid1.addWidget(line2,1,1)
groupBox.setLayout(grid1)
return groupBox
def generate_pscalib_tab_elements(self,str1):
groupBox = QGroupBox(str1)
label1 = QLabel(self)
label1.setText('Serial No:')
line1 = QLineEdit(self)
line1.setText("XXXX")
label2 = QLabel(self)
label2.setText('Chip ID:')
line2 = QLineEdit(self)
line2.setText("XXXX")
label3 = QLabel(self)
label3.setText('QR Code:')
line3 = QLineEdit(self)
line3.setText("XXXX")
label4 = QLabel(self)
label4.setText('Current Range:')
line4 = QLineEdit(self)
line4.setText("1.0")
label5 = QLabel(self)
label5.setText("PS Offset")
line5 = QLineEdit(self)
line5.setText("0.0")
line5.setReadOnly(True)
label6 = QLabel()
label6.setText("PSGain")
line6 = QLineEdit(self)
line6.setText("1.0")
line6.setReadOnly(True)
grid2 = QGridLayout()
grid2.addWidget(label1,0,0)
grid2.addWidget(line1,0,1)
grid2.addWidget(label2,1,0)
grid2.addWidget(line2,1,1)
grid2.addWidget(label3,2,0)
grid2.addWidget(line3,2,1)
grid2.addWidget(label4,3,0)
grid2.addWidget(line4,3,1)
grid2.addWidget(label5,4,0)
grid2.addWidget(line5,4,1)
grid2.addWidget(label6,5,0)
grid2.addWidget(line6,5,1)
groupBox.setLayout(grid2)
return groupBox
def setupUi(self):
self.title = 'BiPolar Power Supply Testing'
self.setWindowTitle(self.title)
print (self.title)
self.left = 50
self.top = 50
self.width = 1000
self.height = 800
self.PSTestTabGrid = QGridLayout()
self.PSCalibTabGrid = QGridLayout()
#self.setGeometry(self.left, self.top, self.width, self.height)
#Create one main box that will hold all the tabs
self.mainbox = QFormLayout()
##################### Items for PS Functional Test Tab #################
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS1"), 0,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS2"), 1,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS3"), 2,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS4"), 3,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS5"), 4,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS6"), 5,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS7"), 6,0)
self.PSTestTabGrid.addWidget(self.generate_pstest_tab_elements("PS8"), 7,0)
self.PSFStart_btn = QPushButton("Start",self)
self.PSFStop_btn = QPushButton("Stop",self)
self.PSTestTabGrid.addWidget(self.PSFStart_btn,8,0)
self.PSTestTabGrid.addWidget(self.PSFStop_btn,9,0)
##################### Items for PS Calib Tab #################
self.PSCalibTabGrid.addWidget(self.generate_pscalib_tab_elements("PS"), 0,0)
self.PSCalibStart_btn = QPushButton("Calib Start",self)
self.PSCalibStop_btn = QPushButton("Calib Stop",self)
self.PSCalibTabGrid.addWidget(self.PSCalibStart_btn,1,0)
self.PSCalibTabGrid.addWidget(self.PSCalibStop_btn,2,0)
######################################################################
#Init Tab Screen
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
#Add Tab
self.tabs.addTab(self.tab1, "PS Tests")
self.tabs.addTab(self.tab2, "PS Calib")
#Set Layout for tab1, tab2
self.tab1.setLayout(self.PSTestTabGrid)
self.tab2.setLayout(self.PSCalibTabGrid)
#Add the Tabs widget to MainBox
self.mainbox.addWidget(self.tabs)
#self.mainbox.addRow(self.tab2HBox)
self.wid = QWidget(self)
self.setCentralWidget(self.wid)
#layout = QtGui.QVBoxLayout()
self.wid.setLayout(self.mainbox)
There are two functions that are being called from SetupUi().
First function is to generate layout for Tab1 by calling generate_pstest_tab_elements()
Second function is to generater layout for Tab2 by calling generate_pscalib_tab_elements()
The spacing between different widgets on Tab2 is very large. I tried calling setVerticalSpacing() to shrink the vertical spacing but it doesnt shrink either.
However If I commment out Tab1 items such that Tab1 doesnt contain any widget then Tab2 items look fine.
It seems like Qt is some how confused between the two independent Grids ?
Attached are the snapshots of the two tabs.
Tab1 image
Tab2 image
Each tab takes the size of the previous tab shown, and in the case of the first tab shown the available size will be used, if you want the smallest size to be taken then you must establish a stretch at the end using a QVBoxLayout.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("BiPolar Power Supply Testing")
tab_widget = QtWidgets.QTabWidget()
self.setCentralWidget(tab_widget)
pstest_widget = QtWidgets.QWidget()
tab_widget.addTab(pstest_widget, "PS Tests")
pstest_vlay = QtWidgets.QVBoxLayout(pstest_widget)
for i in range(1, 9):
title = "PS{}".format(i)
group_box = MainWindow.create_pstest_element(title)
pstest_vlay.addWidget(group_box)
self.PSFStart_btn = QtWidgets.QPushButton("Start")
self.PSFStop_btn = QtWidgets.QPushButton("Stop")
pstest_vlay.addWidget(self.PSFStart_btn)
pstest_vlay.addWidget(self.PSFStop_btn)
pstest_vlay.addStretch()
pscalib_widget = QtWidgets.QWidget()
tab_widget.addTab(pscalib_widget, "PS Calib")
pscalib_vlay = QtWidgets.QVBoxLayout(pscalib_widget)
group_box = MainWindow.create_pscalib_element("PS")
self.PSCalibStart_btn = QtWidgets.QPushButton("Calib Start")
self.PSCalibStop_btn = QtWidgets.QPushButton("Calib Stop")
pscalib_vlay.addWidget(group_box)
pscalib_vlay.addWidget(self.PSCalibStart_btn)
pscalib_vlay.addWidget(self.PSCalibStop_btn)
pscalib_vlay.addStretch()
#staticmethod
def create_pstest_element(title):
group_box = QtWidgets.QGroupBox(title)
grid = QtWidgets.QGridLayout()
group_box.setLayout(grid)
serial_label = QtWidgets.QLabel("Serial No:")
serial_lineedit = QtWidgets.QLineEdit("XXXX")
chipid_label = QtWidgets.QLabel("Chip ID:")
chipid_lineedit = QtWidgets.QLineEdit("XXXX")
rd_group = QtWidgets.QButtonGroup()
rdbtn_FCB15 = QtWidgets.QRadioButton("FCB-15")
rdbtn_DCB15 = QtWidgets.QRadioButton("DCB-15")
grid.addWidget(serial_label, 0, 0)
grid.addWidget(serial_lineedit, 0, 1)
grid.addWidget(rdbtn_FCB15, 0, 2)
grid.addWidget(rdbtn_DCB15, 0, 3)
grid.addWidget(chipid_label, 1, 0)
grid.addWidget(chipid_lineedit, 1, 1)
return group_box
#staticmethod
def create_pscalib_element(title):
group_box = QtWidgets.QGroupBox(title)
flay = QtWidgets.QFormLayout()
group_box.setLayout(flay)
serial_lineedit = QtWidgets.QLineEdit("XXXX")
chipid_lineedit = QtWidgets.QLineEdit("XXXX")
qrcode_lineedit = QtWidgets.QLineEdit("XXXX")
range_lineedit = QtWidgets.QLineEdit("1.0")
offset_lineedit = QtWidgets.QLineEdit("0.0", readOnly=True)
gain_lineedit = QtWidgets.QLineEdit("1.0", readOnly=True)
flay.addRow("Serial No:", serial_lineedit)
flay.addRow("Chip ID:", chipid_lineedit)
flay.addRow("QR Code:", qrcode_lineedit)
flay.addRow("Current Range:", range_lineedit)
flay.addRow("PS Offset:", offset_lineedit)
flay.addRow("PS Gain:", gain_lineedit)
return group_box
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
If you want to continue using QGridLayout then the solution is to place it inside a QVBoxLayout:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("BiPolar Power Supply Testing")
tab_widget = QtWidgets.QTabWidget()
self.setCentralWidget(tab_widget)
pstest_widget = QtWidgets.QWidget()
tab_widget.addTab(pstest_widget, "PS Tests")
grid_lay_1 = QtWidgets.QGridLayout(pstest_widget)
pstest_vlay = QtWidgets.QVBoxLayout()
grid_lay_1.addLayout(pstest_vlay, 0, 0)
for i in range(1, 9):
title = "PS{}".format(i)
group_box = MainWindow.create_pstest_element(title)
pstest_vlay.addWidget(group_box)
self.PSFStart_btn = QtWidgets.QPushButton("Start")
self.PSFStop_btn = QtWidgets.QPushButton("Stop")
pstest_vlay.addWidget(self.PSFStart_btn)
pstest_vlay.addWidget(self.PSFStop_btn)
pstest_vlay.addStretch()
pscalib_widget = QtWidgets.QWidget()
tab_widget.addTab(pscalib_widget, "PS Calib")
grid_lay_2 = QtWidgets.QGridLayout(pscalib_widget)
pscalib_vlay = QtWidgets.QVBoxLayout()
grid_lay_2.addLayout(pscalib_vlay, 0, 0)
group_box = MainWindow.create_pscalib_element("PS")
self.PSCalibStart_btn = QtWidgets.QPushButton("Calib Start")
self.PSCalibStop_btn = QtWidgets.QPushButton("Calib Stop")
pscalib_vlay.addWidget(group_box)
pscalib_vlay.addWidget(self.PSCalibStart_btn)
pscalib_vlay.addWidget(self.PSCalibStop_btn)
pscalib_vlay.addStretch()
# ...

Pyside- Add Widget from another class

I am trying to build a layout using PySide and I have run into a situation where I would like to keep a widget group in a separate class and call it dynamically.
I looked at few examples from this site which sort of gives me an idea but still I am not able to resolve this issue on my own. Here is the sample code of the layout I am building and it will be very helpful if someone can help me solve this issue.
-Thanks in advance
import PySide2.QtCore as QtCore
import PySide2.QtGui as QtGui
import PySide2.QtWidgets as QtGuiWidgets
class TabDialog(QtGuiWidgets.QDialog):
def __init__(self, parent=None):
super(TabDialog, self).__init__(parent)
argument = "Temp"
calldisplay = display_elements()
tabWidget = QtGuiWidgets.QTabWidget()
tabWidget.addTab(tab1(argument), "tab1")
tabWidget.addTab(tab2(argument), "tab2")
buttonBox = QtGuiWidgets.QDialogButtonBox(
QtGuiWidgets.QDialogButtonBox.Ok | QtGuiWidgets.QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QtGuiWidgets.QVBoxLayout()
mainLayout.addWidget(tabWidget)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Load All Elements")
self.show()
class tab1(QtGuiWidgets.QWidget):
def __init__(self, calldisplay, parent=None):
super(tab1, self).__init__(parent)
self.layerfilterGroup = QtGuiWidgets.QLabel("Filter 1")
self.peopleGroup = QtGuiWidgets.QGroupBox("Filter 2")
self.dateGroup = QtGuiWidgets.QGroupBox("Filter 3")
self.loadGroup = QtGuiWidgets.QLabel("Load elements")
self.filterGroup = QtGuiWidgets.QGroupBox("Filters")
self.filterGroup.setGeometry(100, 100, 700, 550)
self.filterLayout = QtGuiWidgets.QVBoxLayout()
for key in range(15):
self.btn = QtGuiWidgets.QCheckBox(str(key))
self.btn.setChecked(True)
self.filterLayout.addWidget(self.btn)
self.filterGroup.setLayout(self.filterLayout)
self.filterscroll = QtGuiWidgets.QScrollArea()
self.fslayout = QtGuiWidgets.QVBoxLayout()
self.filterscroll.setWidget(self.filterGroup)
self.fslayout.addWidget(self.filterscroll)
self.artist = ["All", "N/A", "N/A", "N/A"]
self.acombos = QtGuiWidgets.QComboBox()
self.acombos.addItems(self.artist)
self.all_label = QtGuiWidgets.QLabel()
self.all_label.setText('All')
self.all_label.setGeometry(160, 40, 80, 30)
self.late_label = QtGuiWidgets.QLabel()
self.late_label.setText('Latest')
self.late_label.setGeometry(160, 40, 80, 30)
self.dslider = QtGuiWidgets.QSlider(QtCore.Qt.Horizontal, self)
self.artistlayout = QtGuiWidgets.QVBoxLayout()
self.artistlayout.addWidget(self.acombos)
self.peopleGroup.setLayout(self.artistlayout)
self.datelayout = QtGuiWidgets.QHBoxLayout()
self.datelayout.addWidget(self.all_label)
self.datelayout.addWidget(self.dslider)
self.datelayout.addWidget(self.late_label)
self.dateGroup.setLayout(self.datelayout)
self.rgroup = QtGuiWidgets.QGroupBox("Elements")
self.rgroup.setGeometry(100, 100, 700, 750)
self.rlayout = QtGuiWidgets.QVBoxLayout()
########## This is Working###############
for key in range(15):
self.btn = QtGuiWidgets.QCheckBox(str(key))
self.btn.setChecked(True)
self.rlayout.addWidget(self.btn)
self.rgroup.setLayout(self.rlayout)
############ want to do it this way############
#self.rlayout.addWidget(calldisplay)
#self.rgroup.setLayout(self.rlayout)
self.rscroll = QtGuiWidgets.QScrollArea()
self.rlayout = QtGuiWidgets.QVBoxLayout()
self.rscroll.setWidget(self.rgroup)
self.rlayout.addWidget(self.rscroll)
self.mainLayout = QtGuiWidgets.QVBoxLayout()
self.mainLayout.addWidget(self.layerfilterGroup)
self.mainLayout.addWidget(self.filterscroll)
self.mainLayout.addWidget(self.peopleGroup)
self.mainLayout.addWidget(self.dateGroup)
self.mainLayout.addWidget(self.loadGroup)
self.mainLayout.addWidget(self.rscroll)
self.setLayout(self.mainLayout)
##### call this class dynamically######
class display_elements(QtGuiWidgets.QWidget):
def __init__(self, parent=None):
super(display_elements, self).__init__(parent)
self.rgroup = QtGuiWidgets.QGroupBox("Available Elements")
self.rgroup.setGeometry(400, 400, 700, 750)
self.rlayout = QtGuiWidgets.QVBoxLayout()
for key in range(15):
self.btn = QtGuiWidgets.QCheckBox(str(key))
self.btn.setChecked(True)
self.rlayout.addWidget(self.btn)
self.rgroup.setLayout(self.rlayout)
class tab2(QtGuiWidgets.QWidget):
def __init__(self, fileInfo, parent=None):
super(tab2, self).__init__(parent)
ex = TabDialog()
One of the errors I see is that you point as the first argument of tab1 to calldisplay that I guess is the widget you want to set but you are passing it as an argument to "argument" which is a string, so a first change is to change it .
On the other hand if you are going to use layouts forget about setGeometry() since now the geometry is handled by the QLayouts.
And finally, your display_elements class is not implemented correctly since the rgroup is not added to the widget and for this you must use a layout.
Considering the above, the solution is the following:
import PySide2.QtCore as QtCore
import PySide2.QtGui as QtGui
import PySide2.QtWidgets as QtGuiWidgets
class TabDialog(QtGuiWidgets.QDialog):
def __init__(self, parent=None):
super(TabDialog, self).__init__(parent)
argument = "Temp"
calldisplay = display_elements()
tabWidget = QtGuiWidgets.QTabWidget()
tabWidget.addTab(tab1(calldisplay), "tab1")
tabWidget.addTab(tab2(argument), "tab2")
buttonBox = QtGuiWidgets.QDialogButtonBox(
QtGuiWidgets.QDialogButtonBox.Ok | QtGuiWidgets.QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QtGuiWidgets.QVBoxLayout()
mainLayout.addWidget(tabWidget)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Load All Elements")
self.show()
class tab1(QtGuiWidgets.QWidget):
def __init__(self, calldisplay, parent=None):
super(tab1, self).__init__(parent)
self.layerfilterGroup = QtGuiWidgets.QLabel("Filter 1")
self.peopleGroup = QtGuiWidgets.QGroupBox("Filter 2")
self.dateGroup = QtGuiWidgets.QGroupBox("Filter 3")
self.loadGroup = QtGuiWidgets.QLabel("Load elements")
self.filterGroup = QtGuiWidgets.QGroupBox("Filters")
self.filterGroup.setGeometry(100, 100, 700, 550)
self.filterLayout = QtGuiWidgets.QVBoxLayout()
for key in range(15):
self.btn = QtGuiWidgets.QCheckBox(str(key))
self.btn.setChecked(True)
self.filterLayout.addWidget(self.btn)
self.filterGroup.setLayout(self.filterLayout)
self.filterscroll = QtGuiWidgets.QScrollArea()
self.fslayout = QtGuiWidgets.QVBoxLayout()
self.filterscroll.setWidget(self.filterGroup)
self.fslayout.addWidget(self.filterscroll)
self.artist = ["All", "N/A", "N/A", "N/A"]
self.acombos = QtGuiWidgets.QComboBox()
self.acombos.addItems(self.artist)
self.all_label = QtGuiWidgets.QLabel()
self.all_label.setText('All')
self.all_label.setGeometry(160, 40, 80, 30)
self.late_label = QtGuiWidgets.QLabel()
self.late_label.setText('Latest')
self.late_label.setGeometry(160, 40, 80, 30)
self.dslider = QtGuiWidgets.QSlider(QtCore.Qt.Horizontal, self)
self.artistlayout = QtGuiWidgets.QVBoxLayout()
self.artistlayout.addWidget(self.acombos)
self.peopleGroup.setLayout(self.artistlayout)
self.datelayout = QtGuiWidgets.QHBoxLayout()
self.datelayout.addWidget(self.all_label)
self.datelayout.addWidget(self.dslider)
self.datelayout.addWidget(self.late_label)
self.dateGroup.setLayout(self.datelayout)
self.rgroup = QtGuiWidgets.QGroupBox("Elements")
self.rlayout = QtGuiWidgets.QVBoxLayout()
self.rlayout.addWidget(calldisplay)
self.rgroup.setLayout(self.rlayout)
self.rscroll = QtGuiWidgets.QScrollArea()
self.rlayout = QtGuiWidgets.QVBoxLayout()
self.rscroll.setWidget(self.rgroup)
self.rlayout.addWidget(self.rscroll)
self.mainLayout = QtGuiWidgets.QVBoxLayout()
self.mainLayout.addWidget(self.layerfilterGroup)
self.mainLayout.addWidget(self.filterscroll)
self.mainLayout.addWidget(self.peopleGroup)
self.mainLayout.addWidget(self.dateGroup)
self.mainLayout.addWidget(self.loadGroup)
self.mainLayout.addWidget(self.rscroll)
self.setLayout(self.mainLayout)
class display_elements(QtGuiWidgets.QWidget):
def __init__(self, parent=None):
super(display_elements, self).__init__(parent)
self.rgroup = QtGuiWidgets.QGroupBox("Available Elements")
lay = QtGuiWidgets.QVBoxLayout()
for key in range(15):
btn = QtGuiWidgets.QCheckBox(str(key))
btn.setChecked(True)
lay.addWidget(btn)
rlayout = QtGuiWidgets.QVBoxLayout(self)
rlayout.setContentsMargins(0, 0, 0, 0)
rlayout.addWidget(self.rgroup)
self.rgroup.setLayout(lay)
class tab2(QtGuiWidgets.QWidget):
def __init__(self, fileInfo, parent=None):
super(tab2, self).__init__(parent)
if __name__ == '__main__':
import sys
app = QtGuiWidgets.QApplication(sys.argv)
ex = TabDialog()
ex.show()
sys.exit(app.exec_())

AttributeError: 'Settings' object has no attribute 'scene'

I need to add pixmap to my rectangles. When I press the click button then my pixmap will be added to one by one in my rectangles but I got this attribute error. Can any one please guide me how to solve this error? I tried so many ways but I didn't get the proper output.
Thank you in advance.
Given below is my code:
from pyface.qt import QtGui, QtCore
import sys
global X,Y
class ScanView(QtGui.QGraphicsView):
def __init__(self,X=5, Y=5, parent=None):
super(ScanView, self).__init__(parent)
self.row = X
self.cols = Y
self.squareLB = 50
self.width = Y*self.squareLB+2*self.squareLB
self.height = X*self.squareLB+2*self.squareLB
self.List = []
if self.width>708:
self.scene = QtGui.QGraphicsScene(0,0,self.width,self.height)
for i in range(self.row):
for j in range(self.cols):
item = self.scene.addRect(QtCore.QRectF(0,0,self.squareLB,self.squareLB))
item.setPos(self.squareLB+j*self.squareLB, X*self.squareLB-(i*self.squareLB))
self.List.append(item)
else:
self.scene = QtGui.QGraphicsScene(0,0,708,self.height)
self.marginLR = (708.0-Y*self.squareLB)/2.0
for i in range(self.row):
for j in range(self.cols):
item = self.scene.addRect(QtCore.QRectF(0,0,self.squareLB,self.squareLB))
item.setPos(self.marginLR+j*self.squareLB, X*self.squareLB-(i*self.squareLB))
self.List.append(item)
self.setScene(self.scene)
class Settings(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Settings, self).__init__(parent)
spacer = QtGui.QWidget(self)
spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.vbox = QtGui.QVBoxLayout()
self.save = QtGui.QPushButton("save")
self.open= QtGui.QPushButton("open")
self.folder= QtGui.QPushButton("Folder")
self.folder.clicked.connect(self.showSettings)
self.vbox.addWidget(self.save)
self.vbox.addWidget(self.open)
self.vbox.addWidget(self.folder)
self.grid = QtGui.QGridLayout()
self.grid.addLayout(self.vbox,0,0)
self.scrollArea = QtGui.QScrollArea()
self.scrollArea.setBackgroundRole(QtGui.QPalette.Light)
self.scrollArea.setWidgetResizable(True)
self.grid.addWidget(self.scrollArea,0,1)
self.setCentralWidget(QtGui.QWidget(self))
self.centralWidget().setLayout(self.grid)
self.setGeometry(200,100,300,300)
self.show()
def showSettings(self):
self.MyView = ScanView(5,5)
self.vbox2 = QtGui.QVBoxLayout()
self.Scanbtn1 = QtGui.QPushButton(("click"))
self.Scanbtn1.clicked.connect(self.on_clicked)
self.vbox2.addWidget(self.Scanbtn1)
self.newwidget = QtGui.QWidget()
self.glayout = QtGui.QGridLayout(self.newwidget)
self.glayout.addWidget(self.MyView,0,0)
self.Sw = QtGui.QWidget()
self.Sw.setLayout(self.vbox2)
# self.Sw.setFixedWidth(width - self.scrollArea.viewport().width())
self.glayout.addWidget(self.Sw,0,1)
self.scrollArea.setWidget(self.newwidget)
def on_clicked(self):
print "hellloooooo"
filename1 = "./img/tick.png"
pixmap = QtGui.QPixmap(filename1)
if not pixmap.isNull():
self.MyView.add_pixmap(pixmap)
# pic = QtGui.QPixmap("./img/tick.png")
# scene.addItem(QtGui.QGraphicsPixmapItem(pic))
# # view = self.gv
# self.MyView.setScene(scene)
# self.MyView.setRenderHint(QtGui.QPainter.Antialiasing)
# self.MyView.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Settings()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You have that error because scene does not exist in the Settings class, self.scene is a member of the ScanView class plus self.scene is different from scene.
Going to the problem, you must add as a child of the rectangles and you must also change the size of the pixmap is necessary. To obtain the first rectangle you must store it in a list and then create an iterator.
import sys
from pyface.qt import QtGui, QtCore
class ScanView(QtGui.QGraphicsView):
def __init__(self,X=5, Y=5, parent=None):
super(ScanView, self).__init__(parent)
self._squares = []
n_rows, n_cols = X, Y
squareLB = 50
width, height = (Y + 2)*squareLB, (X + 2)*squareLB
self._scene = QtGui.QGraphicsScene(0, 0, max(708, width), height)
p = squareLB if width > 708 else (708.0-Y*squareLB)/2.0
for i in range(n_rows):
for j in range(n_cols):
it = self._scene.addRect(0, 0, squareLB, squareLB)
it.setPos(p + j*squareLB, i*squareLB)
self._squares.append(it)
self.setScene(self._scene)
class Settings(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Settings, self).__init__(parent)
self.save = QtGui.QPushButton("save")
self.open = QtGui.QPushButton("open")
self.folder = QtGui.QPushButton("Folder", clicked=self.showSettings)
central_widget = QtGui.QWidget()
self.setCentralWidget(central_widget)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.save)
vbox.addWidget(self.open)
vbox.addWidget(self.folder)
self.scrollArea = QtGui.QScrollArea(widgetResizable=True)
self.scrollArea.setBackgroundRole(QtGui.QPalette.Light)
hlay = QtGui.QHBoxLayout(central_widget)
hlay.addLayout(vbox)
hlay.addWidget(self.scrollArea)
self.setGeometry(200, 100, 300, 300)
def showSettings(self):
self.view = ScanView(5, 5)
self.scanbtn = QtGui.QPushButton("click", clicked=self.on_clicked)
self.newwidget = QtGui.QWidget()
hlay = QtGui.QHBoxLayout(self.newwidget)
hlay.addWidget(self.view)
hlay.addWidget(self.scanbtn)
self.scrollArea.setWidget(self.newwidget)
self._iter_squares = iter(self.view._squares)
def on_clicked(self):
filename = "./img/tick.png"
pixmap = QtGui.QPixmap(filename)
if pixmap.isNull():
return
try:
it = next(self._iter_squares)
except StopIteration:
pass
else:
pixmap = pixmap.scaled(it.rect().size().toSize())
pixmap_it = QtGui.QGraphicsPixmapItem(pixmap, it)
def main():
app = QtGui.QApplication(sys.argv)
ex = Settings()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Send class object data to different class

I need help. I created a object in one class and cannot pass the info to a different class.
This is the class I'm trying to make an object with
class BankAccount():
def __init__(self, name, acct):
self.full_name = name
self.acctNum = acct
self.balance = 0
def withdraw(self, w):
self.balance = self.balance - w
w = float(w)
return self.balance
def deposit(self, d):
self.balance = self.balance + d
d = float(d)
return self.balance
def balance(self):
return self.balance()
This the class that is making the object
class Window(QtWidgets.QWidget):
def btnclicked(self):
search_name = self.sender()
if search_name.text() in namecheck:
with open('C:/Users/rbell/PycharmProjects/SDEV140/Final_project/users.txt') as fhand:
for line in fhand:
if search_name.text() in line:
line = line.rstrip('\n')
array = line.split(",")
stringtofloat = float(array[2])
x = BankAccount(array[0], array[1])
x.balance = stringtofloat
print(x.full_name,x.acctNum, x.balance)
self.secwin.show()
else:
print('\nError\n')
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.left = 440
self.top = 260
self.width = 640
self.height = 480
self.lineedit = QtWidgets.QLineEdit("");
self.button1 = QtWidgets.QPushButton("OK");
self.label1 = QtWidgets.QLabel("Welcome to Reese's Bank!\nEnter account number:")
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.label1)
vbox.addWidget(self.lineedit)
self.setLayout(vbox)
self.setGeometry(self.top, self.left, self.width, self.height)
self.setWindowTitle("first window")
self.show()
self.lineedit.editingFinished.connect(self.btnclicked)
self.secwin = secondwindow()
How do I take the x = BankAccount() data and use in another class like
class ViewBalance(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ViewBalance, self).__init__(parent)
self.button1 = QtWidgets.QPushButton("Close");
self.label1 = QtWidgets.QLabel("Your balance is: ")
self.label2 = QtWidgets.QLabel("x.Balance")
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.label1)
vbox.addWidget(self.label2)
vbox.addWidget(self.button1)
self.setLayout(vbox)
The self.label2 is where I would like to display the balance of the x BankAccount object. Do the order of the classes matter? The BankAccount class is at the top under the Imports, the ViewBalance class is under the BankAccount, and the Window Class is at the bottom.
This is the code in its entirety
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
with open('numlist.txt') as f:
namecheck = [line.rstrip('\n') for line in f]
search_name=999
w=0
d=0
sendto=''
class BankAccount():
def __init__(self, name, acct):
self.full_name = name
self.acctNum = acct
self.balance = 0
def withdraw(self, w):
self.balance = self.balance - w
w = float(w)
return self.balance
def deposit(self, d):
self.balance = self.balance + d
d = float(d)
return self.balance
def balance(self):
return self.balance()
# def saveinfo():
# accountname = str(x.full_name)
# accountnumber= str(x.acctNum)
# accountbalance= str(x.balance)
# objectlist= [accountname + ', ' + accountnumber + ', ' + accountbalance]
# savedata = (objectlist[0])
# latestsave= savedata
# with open('users.txt', 'r') as ds:
# with open('tempuserlist.txt', 'w') as es:
# for line in ds:
# if x.acctNum not in line:
# es.write(line)
# with open('users.txt', 'r') as ds:
# with open('lastuseredit.txt', 'w') as es:
# if latestsave not in line:
# es.write('\n')
# es.write(savedata)
# joinfiles=['tempuserlist.txt', 'lastuseredit.txt']
# with open('users.txt', 'w') as output:
# for thing in joinfiles:
# with open(thing) as input:
# output.write(input.read())
class ViewBalance(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ViewBalance, self).__init__(parent)
self.button1 = QtWidgets.QPushButton("Close");
self.label1 = QtWidgets.QLabel("Your balance is: ")
self.label2 = QtWidgets.QLabel("x.Balance")
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.label1)
vbox.addWidget(self.label2)
vbox.addWidget(self.button1)
self.setLayout(vbox)
class DepositMoney(QtWidgets.QWidget):
def __init__(self, parent=None):
super(DepositMoney, self).__init__(parent)
self.button1 = QtWidgets.QPushButton("OK");
self.label1 = QtWidgets.QLabel("How much would you like to deposit? ");
self.lineedit1 = QtWidgets.QLineEdit();
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.label1)
vbox.addWidget(self.lineedit1)
vbox.addWidget(self.button1)
self.setLayout(vbox)
class WithdrawMoney(QtWidgets.QWidget):
def __init__(self, parent=None):
super(WithdrawMoney, self).__init__(parent)
self.button1 = QtWidgets.QPushButton("OK");
self.label1 = QtWidgets.QLabel("How much would you like to withdraw? ");
self.lineedit1 = QtWidgets.QLineEdit();
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.label1)
vbox.addWidget(self.lineedit1)
vbox.addWidget(self.button1)
self.setLayout(vbox)
class secondwindow(QtWidgets.QMainWindow):
def buttonclk(self):
sender = self.sender()
try:
if sender.text() == "View Balance":
self.vb.show()
elif sender.text() == "Deposit":
self.dm.show()
elif sender.text() == "Withdraw":
self.wm.show()
elif sender.text() == "Save/Exit":
exit()
except ValueError:
print("Try again")
def __init__(self):
super(secondwindow, self).__init__()
central_widget = QtWidgets.QWidget()
self.left = 440
self.top = 260
self.width = 640
self.height = 480
self.label1 = QtWidgets.QLabel("Hello x.Full_name");
self.button1 = QtWidgets.QPushButton("View Balance");
self.button2 = QtWidgets.QPushButton("Deposit");
self.button3 = QtWidgets.QPushButton("Withdraw");
self.button4 = QtWidgets.QPushButton("Save/Exit");
hbox = QtWidgets.QHBoxLayout(central_widget)
hbox.addWidget(self.label1)
hbox.addWidget(self.button1)
hbox.addWidget(self.button2)
hbox.addWidget(self.button3)
hbox.addWidget(self.button4)
self.setCentralWidget(central_widget)
self.button1.clicked.connect(self.buttonclk)
self.button2.clicked.connect(self.buttonclk)
self.button3.clicked.connect(self.buttonclk)
self.button4.clicked.connect(self.buttonclk)
self.vb = ViewBalance()
self.dm = DepositMoney()
self.wm = WithdrawMoney()
self.setGeometry(self.top, self.left, self.width, self.height)
self.setWindowTitle("Second window")
class Window(QtWidgets.QWidget):
def btnclicked(self):
search_name = self.sender()
if search_name.text() in namecheck:
with open('users.txt') as fhand:
for line in fhand:
if search_name.text() in line:
line = line.rstrip('\n')
array = line.split(",")
stringtofloat = float(array[2])
x = BankAccount(array[0], array[1])
x.balance = stringtofloat
print(x)
print("it's here")
self.secwin.show()
else:
print('\nError\n')
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.left = 440
self.top = 260
self.width = 640
self.height = 480
self.lineedit = QtWidgets.QLineEdit();
self.label2 = QtWidgets.QLabel("Press enter when ready!");
self.label1 = QtWidgets.QLabel("Welcome to Reese's Bank!\nEnter account number:")
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.label1)
vbox.addWidget(self.lineedit)
vbox.addWidget(self.label2)
self.setLayout(vbox)
self.lineedit.editingFinished.connect(self.btnclicked)
self.secwin = secondwindow()
self.setGeometry(self.top, self.left, self.width, self.height)
self.setWindowTitle("first window")
self.show()
def main():
app = QtWidgets.QApplication(sys.argv)
main = Window()
main.show
sys.exit(app.exec())
if __name__ == '__main__':
main()
The code is reading from, and should write to, two different files to get the premade objects, like Reese, 000, 500.0.
You'll always have to know the name of the instance you are working with.
Here's an example of a mechanism: I do not have PyQt5 installed and the code is not really minimal, but here's how you could set up the mechanism in your code. I have stripped all code not relating to the passing of objects.
Since I have no example data I'm simply assigning what seems to be ok...
class BankAccount(): # Keeps bank account balance
def __init__(self):
self.balance = 445
class ViewBalance(): # Prints variable x of instancewin of class Window
def show(self, b):
print('ViewBalance print b:', b)
class Window():
def __init__(self):
x = BankAccount() # Creates instance x of class BankAccount
print('Window print x.balance:', x.balance)
self.vb = ViewBalance()
self.vb.show(x.balance) # Call instance vb of class ViewBalance
# to show balance
win = Window()

pySide QComboBox refresh

from PySide import QtGui, QtCore
def listItems():
itemList = ("first","second","etc..")
return itemList
class tabDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
tabWidget = QtGui.QTabWidget()
tabWidget.addTab(mainTab(), self.tr("Main"))
tabWidget.addTab(secondTab(), self.tr("Second "))
mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(tabWidget)
self.setLayout(mainLayout)
class mainTab(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.createGroup = QtGui.QGroupBox(self.tr("Add Item to list"))
self.fileNameEdit = QtGui.QLineEdit(self)
self.fileNameEdit.setPlaceholderText("new item")
self.createButton = QtGui.QPushButton('add',self)
#self.createButton.clicked.connect(self.additemToList)
self.createLayout = QtGui.QGridLayout()
self.createLayout.addWidget(self.fileNameEdit,1,2)
self.createLayout.addWidget(self.createButton,1,3)
self.setLayout(self.createLayout)
self.createGroup.setLayout(self.createLayout)
self.addGroup = QtGui.QGroupBox(self.tr("list items"))
self.projectLabel = QtGui.QLabel(self.tr("item : "))
self.projectListCombo = QtGui.QComboBox(self)
self.projectListCombo.addItems(listItems())
self.addLayout = QtGui.QHBoxLayout()
self.addLayout.addWidget(self.projectLabel)
self.addLayout.addWidget(self.projectListCombo)
self.addGroup.setLayout(self.addLayout)
self.mainLayout = QtGui.QVBoxLayout()
self.mainLayout.addWidget(self.createGroup)
self.mainLayout.addWidget(self.addGroup)
self.setLayout(self.mainLayout)
class secondTab(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.initUI()
def initUI(self):
self.addGroup = QtGui.QGroupBox(self.tr("list items"))
self.projectLabel = QtGui.QLabel(self.tr("item : "))
self.projectListCombo = QtGui.QComboBox(self)
self.projectListCombo.addItems(listItems())
self.addLayout = QtGui.QHBoxLayout()
self.addLayout.addWidget(self.projectLabel)
self.addLayout.addWidget(self.projectListCombo)
self.addGroup.setLayout(self.addLayout)
self.mainLayout = QtGui.QVBoxLayout()
self.mainLayout.addWidget(self.addGroup)
self.setLayout(self.mainLayout)
tabdialog = tabDialog()
tabdialog.show()
Have 2 tabs .In first tab is line for text , button for add item and combo box and in second tab is just combo box.
Both combo box contain same list items.
If add item to list ,need refresh both combo box
You can use QComboBox::addItem:
from PySide import QtGui, QtCore
import sys
def listItems():
itemList = ("first","second","etc..")
return itemList
class tabDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.tabWidget = QtGui.QTabWidget()
self.mainTab = mainTab(self)
self.secondTab = secondTab(self)
self.tabWidget.addTab(self.mainTab, self.tr("Main"))
self.tabWidget.addTab(self.secondTab, self.tr("Second "))
mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(self.tabWidget)
self.setLayout(mainLayout)
def additemToList(self):
item = self.mainTab.fileNameEdit.text()
self.mainTab.projectListCombo.addItem(item)
self.secondTab.projectListCombo.addItem(item)
class mainTab(QtGui.QWidget):
def __init__(self, parent=tabDialog):
QtGui.QWidget.__init__(self, parent)
self.q = 1234
self.createGroup = QtGui.QGroupBox(self.tr("Add Item to list"))
self.fileNameEdit = QtGui.QLineEdit(self)
self.fileNameEdit.setPlaceholderText("new item")
self.createButton = QtGui.QPushButton('add',self)
self.createButton.clicked.connect(parent.additemToList)
self.createLayout = QtGui.QGridLayout()
self.createLayout.addWidget(self.fileNameEdit,1,2)
self.createLayout.addWidget(self.createButton,1,3)
self.setLayout(self.createLayout)
self.createGroup.setLayout(self.createLayout)
self.addGroup = QtGui.QGroupBox(self.tr("list items"))
self.projectLabel = QtGui.QLabel(self.tr("item : "))
self.projectListCombo = QtGui.QComboBox(self)
self.projectListCombo.addItems(listItems())
self.addLayout = QtGui.QHBoxLayout()
self.addLayout.addWidget(self.projectLabel)
self.addLayout.addWidget(self.projectListCombo)
self.addGroup.setLayout(self.addLayout)
self.mainLayout = QtGui.QVBoxLayout()
self.mainLayout.addWidget(self.createGroup)
self.mainLayout.addWidget(self.addGroup)
self.setLayout(self.mainLayout)
class secondTab(QtGui.QWidget):
def __init__(self, parent=tabDialog):
QtGui.QWidget.__init__(self, parent)
self.initUI()
def initUI(self):
self.addGroup = QtGui.QGroupBox(self.tr("list items"))
self.projectLabel = QtGui.QLabel(self.tr("item : "))
self.projectListCombo = QtGui.QComboBox(self)
self.projectListCombo.addItems(listItems())
self.addLayout = QtGui.QHBoxLayout()
self.addLayout.addWidget(self.projectLabel)
self.addLayout.addWidget(self.projectListCombo)
self.addGroup.setLayout(self.addLayout)
self.mainLayout = QtGui.QVBoxLayout()
self.mainLayout.addWidget(self.addGroup)
self.setLayout(self.mainLayout)
def main():
app = QtGui.QApplication(sys.argv)
tabdialog = tabDialog()
tabdialog.show()
app.exec_()
if __name__ == '__main__':
main()
I made ​​the following changes:
mainTab and secondTab in tabDialog are instance attributes
mainTab and secondTab get tabDialog as a parent
Added additemToList in tabDialog
In mainTab.__init__(): self.createButton.clicked.connect(parent.additemToList)

Categories

Resources