binding a signal to QListWidget items - python

How do I make sure that clicking on a QListWidget item opens the corresponding widgets in the QFrame and that the data entered in these widgets is saved between switching list items?
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
tab_widget = QTabWidget()
tab_widget.setStyleSheet('background-color:gainsboro')
tab_widget.addTab(Setup(), "setup")
vbox.addWidget(tab_widget)
self.setLayout(vbox)
class Setup(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout()
splitter = QSplitter(Qt.Horizontal)
self.list = QListWidget()
self.list.setStyleSheet("background-color:white")
QListWidgetItem("vertices", self.list)
QListWidgetItem("blocks", self.list)
self.list.itemClicked.connect(self.conv_met)
splitter.addWidget(self.list)
self.frame = QFrame()
self.frame.setFrameShape(QFrame.StyledPanel)
self.frame.setLineWidth(0.6)
splitter.addWidget(self.frame)
hbox.addWidget(splitter)
self.setLayout(hbox)
self.show()
def conv_met(self, item):
if item.text() == "vertices":
convertToMeters_layout = QHBoxLayout()
convertToMeters_lbl = QLabel("convertToMeters")
convertToMeters_val = QLineEdit("0.1")
convertToMeters_layout.addWidget(convertToMeters_lbl)
convertToMeters_layout.addWidget(convertToMeters_val)
self.frame.setLayout(convertToMeters_layout)
if item.text() == "blocks":
block_grad_layout = QGridLayout()
hexx = QComboBox(self)
hexx.addItems(["hex"])
ver_labels = QLineEdit("0 1 2 3 4 5 6 7")
block_grad_layout.addWidget(hexx, 0, 0)
block_grad_layout.addWidget(ver_labels, 0, 1)
self.frame.setLayout(block_grad_layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = Window()
main_win.show()
sys.exit(app.exec_())

In order to keep data for an item, you can use setData(role, value) to store the previous entered data and before changing to the new current item.
Note that you should not use setLayout() more than once; in fact, your example doesn't work as expected for this reason, and you could see the error message if you run it from a shell or command prompt:
QWidget::setLayout: Attempting to set QLayout "" on QFrame "", which already has a layout
To achieve what you want, the solution is to use QStackedWidget, which works almost like a QTabWidget, but doesn't have a tab bar to switch between "pages", as they can only be changed programmatically using setCurrentIndex() or setCurrentWidget().
class Setup(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout()
splitter = QSplitter(Qt.Horizontal)
self.list = QListWidget()
self.list.setStyleSheet("background-color:white")
self.verticesItem = QListWidgetItem("vertices", self.list)
self.blocksItem = QListWidgetItem("blocks", self.list)
self.list.itemClicked.connect(self.conv_met)
splitter.addWidget(self.list)
self.frame = QFrame()
self.frame.setFrameShape(QFrame.StyledPanel)
self.frame.setLineWidth(0.6)
frameLayout = QVBoxLayout(self.frame)
self.stackedWidget = QStackedWidget()
frameLayout.addWidget(self.stackedWidget)
self.convertToMeters_widget = QWidget()
self.stackedWidget.addWidget(self.convertToMeters_widget)
convertToMeters_layout = QHBoxLayout(self.convertToMeters_widget)
convertToMeters_lbl = QLabel("convertToMeters")
self.convertToMeters_val = QLineEdit("0.1")
convertToMeters_layout.addWidget(convertToMeters_lbl)
convertToMeters_layout.addWidget(self.convertToMeters_val)
self.block_grad_widget = QWidget()
self.stackedWidget.addWidget(self.block_grad_widget)
block_grad_layout = QGridLayout(self.block_grad_widget)
hexx = QComboBox()
hexx.addItems(["hex"])
self.ver_labels = QLineEdit("0 1 2 3 4 5 6 7")
block_grad_layout.addWidget(hexx, 0, 0)
block_grad_layout.addWidget(self.ver_labels, 0, 1)
splitter.addWidget(self.frame)
hbox.addWidget(splitter)
self.setLayout(hbox)
self.currentItem = None
def conv_met(self, item):
if self.currentItem:
if self.currentItem == self.verticesItem:
self.currentItem.setData(Qt.UserRole, self.convertToMeters_val.text())
else:
self.currentItem.setData(Qt.UserRole, self.ver_labels.text())
if item == self.currentItem:
return
self.currentItem = item
if item == self.verticesItem:
self.stackedWidget.setCurrentWidget(self.convertToMeters_widget)
self.convertToMeters_val.setText(item.data(Qt.UserRole) or '0.1')
elif item == self.blocksItem:
self.stackedWidget.setCurrentWidget(self.block_grad_widget)
self.ver_labels.setText(item.data(Qt.UserRole) or '0 1 2 3 4 5 6 7')
Note that if you want to store numeric values for the "vertices", you might prefer to use a QSpinBox (or QDoubleSpinBox for floating numbers). Similarly, if you need only hexadecimal values, it's better to set an inputMask or add a validator to ensure that the entered values are valid.

Related

Pyqt5: How to set the size of layout in QStackedLayout or QStackedWidget

I am pretty new to pyqt5.
I have a question regarding qstacklayout. It might be the same question as the How to make different pages of a QStackedWidget of different sizes?
Let's assume that I have done this as below
class MainUI(QDialog)
def __init__(self, parent=None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.scroll_area=QScrollArea()
self.main_layout=QHBoxLayout()
self.scroll_area.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget()
self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 500, 300))
self.grid_layout = QGridLayout()
self.grid_layout.addWidget(self.a_widget_ui(), 0, 0)
... # Set other widget to grid_layout in position of (1, 0), (2, 0), (3, 0)
self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
#set the buttonbox at the end of gridlayout
self.grid_layout.addWidget(self.button_box, 4, 0)
self.setLayout(self.main_layout)
self.setGeometry(300, 300, 790, 800)
def self.a_widget_ui(self):
group_box = QGroupBox('A Information')
a_list = ['1', '2', '3']
self.combo_box = QComboBox()
self.combo_box.addItems(a_list)
self.combo_box.activated[str].connect(self.update_widget)
self.stacked_layout = QStackedLayout()
self.A_layout = A_Layout()
self.B_layout = B_Layout()
self.stacked_layout.addWidget(self.A_Layout)
self.stacked_layout.addWidget(self.B_Layout)
hbox = QHBoxLayout()
hbox.addWidget(self.combo_box)
vbox = QVBoxLayout()
vbox.addLayout(hbox)
vbox.addLayout(self.stacked_layout)
group_box.setLayout(vbox)
return groupbox
def update_widget(self, choice):
if choice == "A":
self.stacked_layout.setCurrentWidget(self.A_Layout)
else:
self.stacked_layout.setCurrentWidget(self.B_Layout)
Then I have these different layouts for A_Layout() and B_Layout()
class A_Layout(QWidget):
def __init__(self, parent=None)
super().__init__(parent)
grid_layout = QGridLayout()
grid_layout.addWidget(self.set_a_widget(), 0, 0)
self.setLayout(grid_layout)
def set_a_widget(self):
main_widget = QWidget()
self._a_attrib = QLineEdit()
self._b_attrib = QLineEdit()
form_layout = QFormedLayout()
form_layout.addWidget('set a attrib', self._a_attrib)
form_layout.addWidget('set b attrib', self._b_attrib)
main_widget.setLayout(form_layout)
return main_widget
class B_Layout(QWidget):
def __init__(self, parent=None)
super().__init__(parent)
grid_layout = QGridLayout()
grid_layout.addWidget(self.set_a_widget(), 0, 0)
self.setLayout(grid_layout)
def set_a_widget(self):
main_widget = QWidget()
self._a_attrib = QLineEdit()
self._b_attrib = QLineEdit()
self._c_attrib = QLineEdit()
self._d_attrib = QLineEdit()
form_layout = QFormedLayout()
form_layout.addWidget('set a attrib', self._a_attrib)
form_layout.addWidget('set b attrib', self._b_attrib)
form_layout.addWidget('set c attrib', self._c_attrib)
form_layout.addWidget('set d attrib', self._d_attrib)
main_widget.setLayout(form_layout)
return main_widget
There are some conditions that I've made when I was making this structure.
I made class A_Layout and class B_Layout in order for me to reuse those Dialog later if needed.
I used QStackedLayout / QStackedWidget in order for me to update the layout/widget via combobox.
My questions are the following.
Is it possible for me to change the layout size dynamically? For example, as you can tell that the size of layout will be different between A_Layout and B_Layout due to the number of components.
Since I am pretty new, but I have a hunch that I am doing it completely wrong about using qstackedwidget, maybe I should customize the layout such that it would work as qstackedlayout but has more size management
I would sincerely want to get advice or suggestions if it's possible. What I have tried is to put QSizePolicy before adding layout/widget in stackedlayout and put them whenever I call update_widget. Any other tip or advice would be very appreciated.

Inputs from QFormLayout are printing empty

My program collecting some data from the user (patient ID, trial no., activity, etc.) using a dialog window with a QFormLayout. I want to save these data and print them onto the main window, but when I print them they come out empty. I'm new to Python so I'm wondering if there's a structural issue with my code that is causing the variables to be lost.
I have a main class for the main window that looks like this (there is more but I cut out irrelevant parts):
class App(QMainWindow):
""" Sets up the main window for the Graphical User Interface """
def __init__(self):
super().__init__()
self.title = 'Title'
self.left = 60
self.top = 100
self.width = 1400
self.height = 820
self.initUI()
def initUI(self) :
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
*lots of labels and buttons added here*
inputs = getInputs()
inputs.exec()
patID = inputs.patID
patAct = inputs.patAct
patTrial = inputs.patTrial
# print out inputs under their labels
label_pat2 = QLabel(str(patID), self)
label_pat2.move(150, 200)
label_activity2 = QLabel(str(patAct), self)
label_activity2.move(300, 200)
label_trial2= QLabel(str(patTrial), self)
label_trial2.move(500, 200)
self.show() # show main window
Then I have another class that opens a dialog window to get the inputs, which looks like this:
class getInputs(QDialog):
""" Takes in the patient ID number, trial number, and patient activity """
# NumGridRows = 3
# NumButtons = 4
def __init__(self):
super().__init__()
# super(getInputs, self).__init__()
self.createFormGroupBox()
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.formGroupBox)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Trial information Input Dialog")
self.resize(400,200)
def createFormGroupBox(self):
combo_box = QComboBox()
combo_box.addItem("Walking")
combo_box.addItem("Running")
combo_box.addItem("Slow Walking")
line_edit = QLineEdit()
spin_box = QSpinBox()
self.formGroupBox = QGroupBox("Form layout")
layout = QFormLayout()
layout.addRow(QLabel("Patient ID:"), line_edit)
layout.addRow(QLabel("Activity:"), combo_box)
layout.addRow(QLabel("Trial no.:"), spin_box)
self.formGroupBox.setLayout(layout)
self.patID = line_edit.text()
self.patAct = combo_box.currentText()
self.patTrial = spin_box.text()
My theories right now are that there is either an error in my structure that causes the results from the window to be deleted, or that the .text() and .currentText() functions might not be the right function to use.
The problem is that you are getting the data an instant after creating the widgets when the user still does not interact with the QDialog. On the other hand, to obtain the value of the QSpinBox you must use the value() method:
class getInputs(QDialog):
"""Takes in the patient ID number, trial number, and patient activity"""
# NumGridRows = 3
# NumButtons = 4
def __init__(self):
super().__init__()
# super(getInputs, self).__init__()
self.createFormGroupBox()
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.formGroupBox)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Trial information Input Dialog")
self.resize(400, 200)
def createFormGroupBox(self):
self.combo_box = QComboBox()
self.combo_box.addItem("Walking")
self.combo_box.addItem("Running")
self.combo_box.addItem("Slow Walking")
self.line_edit = QLineEdit()
self.spin_box = QSpinBox()
self.formGroupBox = QGroupBox("Form layout")
layout = QFormLayout()
layout.addRow(QLabel("Patient ID:"), self.line_edit)
layout.addRow(QLabel("Activity:"), self.combo_box)
layout.addRow(QLabel("Trial no.:"), self.spin_box)
self.formGroupBox.setLayout(layout)
def exec(self):
super().exec()
self.patID = self.line_edit.text()
self.patAct = self.combo_box.currentText()
self.patTrial = self.spin_box.value()

PyQt4 - QLineEdit() and QCheckbox()

I am building a GUI for obtaining user inputs and then using them in some complex step later. I have a group of checkboxes from which the user has to choose at least one and also provide an 'alias' name for it in the QLineEdit right below the checkbox (default name is taken otherwise).
Currently, I have to first enter the alias name and then check the checkbox to register the entered name in the line edit to get the value entered by the user and connected checkbox name. This order is not normal.
Is there a way to get the Editline data and the connected checkbox name when 'Continue' is clicked?
Here is my code:
from PyQt4 import QtGui, QtCore
import sys
checkpoint_list = ['Amsterdam','Munich','Paris','Mumbai']
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
self.final_list = []
self.platform_list = {}
self.qem = None
def initUI(self):
lay_out = QtGui.QVBoxLayout(self)
# select the CPs
cp_lbl = QtGui.QLabel("Please select CP versions to compare:", self)
lay_out.addWidget(cp_lbl)
self.cb = []
self.platform_label = []
i = 0
for cp in checkpoint_list:
self.cb.append(QtGui.QCheckBox(cp, self))
self.platform_label.append(QtGui.QLineEdit(cp, self))
self.cb[i].stateChanged.connect(self.clickBoxStateChanged)
lay_out.addWidget(self.cb[i])
lay_out.addWidget(self.platform_label[i])
i += 1
lay_out.addStretch(10)
# Continue and cancel button
btn_cancel = QtGui.QPushButton('Cancel', self)
btn_continue = QtGui.QPushButton('Continue', self)
hbox = QtGui.QHBoxLayout()
hbox.addStretch()
hbox.addWidget(btn_continue)
hbox.addWidget(btn_cancel)
vbox = QtGui.QVBoxLayout()
vbox.addStretch()
lay_out.addLayout(hbox)
lay_out.addLayout(vbox)
self.setLayout(lay_out)
btn_cancel.clicked.connect(self.onclick_cancel)
btn_cancel.setToolTip('To <b>Cancel</b> with this process')
btn_continue.clicked.connect(self.onclick_Continue)
btn_continue.setToolTip('To <b>Continue</b> with the matching')
# Screen show
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle('CP Selection Window')
self.show()
def clickBoxStateChanged(self, cb):
self.final_list = []
self.platform_list = {}
for i in range(len(self.cb)):
if self.cb[i].isChecked():
if self.cb[i] not in self.final_list:
self.final_list.append(str(self.cb[i].text()))
self.platform_list[str(self.cb[i].text())] = str(self.platform_label[i].text())
print self.final_list
print self.platform_list
elif self.cb[i].isChecked() == False:
if self.cb[i].text() in self.final_list:
self.final_list.remove(str(self.cb[i].text()))
del self.platform_list[str(self.cb[i].text())]
print self.final_list
print self.platform_list
def onclick_Continue(self):
try:
if len(self.final_list) == 0:
self.qem = QtGui.QErrorMessage(self)
self.qem.showMessage("Please select at least 1 checkpoint to continue...")
else:
self.close()
except:
print "No CP was selected..."
def onclick_cancel(self):
sys.exit()
if __name__ == "__main__":
# GUI code
app = QtGui.QApplication(sys.argv)
w = MyGui()
app.exec_()
The simplest solution is to create a method that analyzes the information and that returns a dictionary of the selected elements:
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
def initUI(self):
lay_out = QtGui.QVBoxLayout(self)
# select the CPs
cp_lbl = QtGui.QLabel("Please select CP versions to compare:")
lay_out.addWidget(cp_lbl)
self.cb = []
self.platform_label = []
for cp in checkpoint_list:
cb = QtGui.QCheckBox(cp)
le = QtGui.QLineEdit(cp)
lay_out.addWidget(cb)
lay_out.addWidget(le)
self.cb.append(cb)
self.platform_label.append(le)
lay_out.addStretch(10)
# Continue and cancel button
btn_cancel = QtGui.QPushButton("Cancel")
btn_continue = QtGui.QPushButton("Continue")
hbox = QtGui.QHBoxLayout()
hbox.addStretch()
hbox.addWidget(btn_continue)
hbox.addWidget(btn_cancel)
vbox = QtGui.QVBoxLayout()
vbox.addStretch()
lay_out.addLayout(hbox)
lay_out.addLayout(vbox)
btn_cancel.clicked.connect(self.onclick_cancel)
btn_cancel.setToolTip("To <b>Cancel</b> with this process")
btn_continue.clicked.connect(self.onclick_Continue)
btn_continue.setToolTip("To <b>Continue</b> with the matching")
# Screen show
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle("CP Selection Window")
self.show()
def get_elements_selected(self):
values_selected = dict()
for cb, le in zip(self.cb, self.platform_label):
if cb.isChecked():
values_selected[cb.text()] = le.text()
return values_selected
def onclick_Continue(self):
values = self.get_elements_selected()
if values:
print(values)
self.close()
else:
qem = QtGui.QErrorMessage(self)
qem.showMessage("Please select at least 1 checkpoint to continue...")
qem.exec_()
def onclick_cancel(self):
sys.exit()

How to add table widget in a QtoolBox item?

I'm working in a simple gui with a QtoolBox can increase the item dynamically (with button "add item"). I need to add, for each item, a new widget like table (for example TableView class) but I can't understand how can I do it. Could anybody help me? (follow the code I wrote until now)
from PyQt5.QtWidgets import *
import sys
data = {'col1':['1','2','3','4'],
'col2':['1','2','1','3'],
'col3':['1','1','2','1']}
class TableView(QTableWidget):
def __init__(self, data, *args):
QTableWidget.__init__(self, *args)
self.data = data
self.setData()
self.resizeColumnsToContents()
self.resizeRowsToContents()
def setData(self):
horHeaders = []
for n, key in enumerate(sorted(self.data.keys())):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)
class Window(QWidget):
def __init__(self):
super().__init__()
self.layout = QGridLayout()
self.setLayout(self.layout)
self.numAddWidget = 1
self.initUi()
# Add toolbar and items
def initUi(self):
self.add_button = QPushButton("Add Widget")
self.layout.addWidget(self.add_button, 0, 0)
self.add_button.clicked.connect(self.addPage)
self.toolbox = QToolBox()
self.layout.addWidget(self.toolbox, 1, 0)
def addPage(self):
self.numAddWidget += 1
label = QLabel()
a=self.toolbox.addItem(label, "item {}".format(self.numAddWidget))
self.table=TableView(data, 4, 3)
self.toolbox.addWidget(self.table)
print(a)
app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())

Dynamic Widget Addition in PyQt

I'm new to PyQt and I'm trying to create a system which dynamically adds widgets when the user presses add.
I want the same self.comboBox widget to get added above the Add button. I will also make a remove button but I believe that will be no problem.
Moreover, I would like certain checkboxes to appear next to the self.combobox when the user chooses an option (aka option is not -Select-).
Finally, how can I store the user's choices in the checkboxes and the combobox? Do I declare a variable or what exactly?
My code was too much to read, so this instead:
class myWindow(QWidget):
def __init__(self):
super().__init__()
self.init()
self.organize()
def init(self):
self.label = QLabel("Label")
self.comboBox = QComboBox(self)
self.comboBox.addItem("-Select-")
self.comboBox.addItem("1")
self.comboBox.addItem("2")
self.comboBox.addItem("3")
self.addbtn = QPushButton("Add")
self.addbtn.clicked.connect(self.addComboBox)
def organize(self):
grid = QGridLayout(self)
self.setLayout(grid)
grid.addWidget(Label, 0, 0, 0, 2)
grid.addWidget(self.comboBox, 1, 2, 1, 3)
grid.addWidget(self.addbtn, 2, 2)
def addComboBox(self):
#Code to add a combo box just like self.comboBox above addbtn and below all existing comboBoxes.
What I want
Sorry. If I understand you correctly, your example might look something like this:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class CheckableComboBox(QComboBox):
def __init__(self, parent = None):
super(CheckableComboBox, self).__init__(parent)
self.parent = parent
self.setView(QListView(self))
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == Qt.Checked:
item.setCheckState(Qt.Unchecked)
else:
item.setCheckState(Qt.Checked)
self.on_selectedItems()
def checkedItems(self):
checkedItems = []
for index in range(self.count()):
item = self.model().item(index)
if item.checkState() == Qt.Checked:
checkedItems.append(item)
return checkedItems
def on_selectedItems(self):
selectedItems = self.checkedItems()
self.parent.lblSelectItem.setText("")
for item in selectedItems:
self.parent.lblSelectItem.setText("{} {} "
"".format(self.parent.lblSelectItem.text(), item.text()))
class ExampleWidget(QGroupBox):
def __init__(self, numAddWidget):
QGroupBox.__init__(self)
self.numAddWidget = numAddWidget
self.numAddItem = 1
self.setTitle("Title {}".format(self.numAddWidget))
self.initSubject()
self.organize()
def initSubject(self):
self.lblName = QLabel("Label Title {}".format(self.numAddWidget), self)
self.lblSelectItem = QLabel(self)
self.teachersselect = CheckableComboBox(self)
self.teachersselect.addItem("-Select {}-".format(self.numAddItem))
item = self.teachersselect.model().item(0, 0)
item.setCheckState(Qt.Unchecked)
self.addbtn = QPushButton("ComboBoxAddItem...", self)
self.addbtn.clicked.connect(self.addTeacher)
def organize(self):
grid = QGridLayout(self)
self.setLayout(grid)
grid.addWidget(self.lblName, 0, 0, 1, 3)
grid.addWidget(self.lblSelectItem, 1, 0, 1, 2)
grid.addWidget(self.teachersselect, 1, 2)
grid.addWidget(self.addbtn, 3, 2)
def addTeacher(self):
self.numAddItem += 1
self.teachersselect.addItem("-Select {}-".format(self.numAddItem))
item = self.teachersselect.model().item(self.numAddItem-1, 0)
item.setCheckState(Qt.Unchecked)
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.numAddWidget = 1
self.initUi()
def initUi(self):
self.layoutV = QVBoxLayout(self)
self.area = QScrollArea(self)
self.area.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget()
self.scrollAreaWidgetContents.setGeometry(0, 0, 200, 100)
self.layoutH = QHBoxLayout(self.scrollAreaWidgetContents)
self.gridLayout = QGridLayout()
self.layoutH.addLayout(self.gridLayout)
self.area.setWidget(self.scrollAreaWidgetContents)
self.add_button = QPushButton("Add Widget")
self.layoutV.addWidget(self.area)
self.layoutV.addWidget(self.add_button)
self.add_button.clicked.connect(self.addWidget)
self.widget = ExampleWidget(self.numAddWidget)
self.gridLayout.addWidget(self.widget)
self.setGeometry(700, 200, 350, 300)
def addWidget(self):
self.numAddWidget += 1
self.widget = ExampleWidget(self.numAddWidget)
self.gridLayout.addWidget(self.widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyApp()
w.show()
sys.exit(app.exec_())

Categories