I'm trying to create an animation to hide unselected rows in a QTableWidget.
I want the height of the rows to decrease until it is 0, for a smoother transition.
I found the following in C++ that does exactly what I'm trying to achieve, but I cannot get the same result in Python: https://forum.qt.io/topic/101437/animate-qtablewidget/4
I noticed they use Q_PROPERTY, but I honestly do not understand how it works...
Here what I came up for now (the animation is not working):
`
import sys
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtCore import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.resize(600,200)
self.initUI()
def initUI(self):
layout = QHBoxLayout()
self.table = QTableWidget()
self.table.setColumnCount(3)
tableLabels = ["First Name", "Surname", "Age"]
self.table.setHorizontalHeaderLabels(tableLabels)
self.table.setRowCount(3)
self.table.verticalHeader().setMinimumSectionSize(1)
users = {
'0': ["peter", "parker", "19"],
'1': ["bruce", "banner", "42"],
'2': ["barry", "allen", "35"]
}
for row, data in users.items():
for column, value in enumerate(data):
self.table.setItem(int(row), column, QTableWidgetItem(value))
button1 = QPushButton("Hide")
button1.clicked.connect(lambda: self.hide_row())
layout.addWidget(self.table)
layout.addWidget(button1)
self.setLayout(layout)
self.show()
def hide_row(self):
for i in [x for x in range(self.table.rowCount()) if x != self.table.currentRow()]:
self.rowHeight = QPropertyAnimation(self.table.item(i, 0), b"geometry")
self.rowHeight.setDuration(400)
self.rowHeight.setStartValue(QRect(0, 0, 0, self.table.rowHeight(i)))
self.rowHeight.setEndValue(QRect(0, 0, 0, 0))
self.rowHeight.start()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
`
Any idea how to achieve this goal in Python?
A Qt animation requires that the parent (or target, in the case of a Property Animation) inherits from QObject, and table widget items do not.
Also, the geometry property should exist for the target object, and items do not have such a property.
The solution is to use a QVariantAnimation and use the valueChanged signal to set the row height on the table.
class Example(QWidget):
def __init__(self):
super().__init__()
self.resize(600,200)
self.initUI()
self.animation = QVariantAnimation(self)
self.animation.setDuration(400)
self.animation.valueChanged.connect(self.animationChanged)
self.animation.finished.connect(self.finished)
def animationChanged(self, height):
self.table.setRowHeight(self.currentRow, height)
def finished(self):
self.table.setRowHidden(self.currentRow, True)
# reset the height, so that we can use it as a "stored" value in case
# we want to show the row again
self.table.setRowHeight(self.currentRow, self.currentHeight)
def hide_row(self):
# ignore if the animation is already resizing a row
if self.animation.state():
return
self.currentRow = self.table.currentRow()
self.currentHeight = self.table.rowHeight(self.currentRow)
self.animation.setStartValue(self.currentHeight)
self.animation.setEndValue(1)
self.animation.start()
# ...
Related
I have a complex program in which I need to connect multiple windows. Unfortunately, I seem to be not fully understanding the concept/steps necessary to do this so bonus points if anyone can explain the steps/process well. In my current program, I have a list of items. Once I select them by moving them over to the right list widget, I need them to go to the third window. The third window should be activated by clicking the dots on the second window. The program runs and shows the second window appropriately but the signal/slot connection of the dots button does not work. However, the rest of the code is working because if I switch the toolkit to show the third window, that part is performing as expected. My code is below, and again, no errors are being returned, but clicking the dots button on the second window does nothing.
Also, a question - do I instantiate the third window within the second class, or only within the main window? Again, struggling to fully understand the process and I will need to do this multiple more times.
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QListWidget, QLineEdit, QTextEdit, QGridLayout, QHBoxLayout, QVBoxLayout, QSizePolicy, QFileDialog, QTabWidget, QCheckBox
import PyQt5.QtGui as qtg
import glob
import os
from PyQt5.QtCore import Qt, QSettings
import inspect
from PyQt5 import QtCore
import pandas as pd
import pathlib
import pyreadstat
import json
class ThirdWindow(QWidget):
def __init__(self):
super().__init__()
self.layout = QGridLayout()
self.setLayout(self.layout)
self.allVariables = QListWidget()
self.variablesSelected = QListWidget()
#self.allVariables.insertItem(0, 'Hello')
self.layout.addWidget(self.allVariables, 1,0)
self.layout.addWidget(self.variablesSelected, 1, 1)
def setItems(self, items):
self.allVariables.clear()
for item in items:
self.allVariables.addItem(item)
class SecondWindow(QWidget):
def __init__(self):
super().__init__()
##not sure if I am supposed to instantiate this here or only in the main window class
self.thirdWindow = ThirdWindow()
self.layout = QGridLayout(self)
self.by = QLabel("By")
self.byVariables = QLineEdit()
self.byButton = QPushButton("...")
self.layout.addWidget(self.by, 1, 0)
self.layout.addWidget(self.byVariables, 2, 0)
self.layout.addWidget(self.byButton, 2, 1)
def seconddWindowConnections(self):
self.byButton.clicked.connect(self.show_third_window)
#self.buttons['Toolkit'].clicked.connect(self.show_new_window)
def show_third_window(self):
self.thirdWindow.show()
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Add a title
self.setWindowTitle("GUI Querying Program")
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.initUI()
self.setButtonConnections()
self.sw = SecondWindow()
self.tw = ThirdWindow()
def initUI(self):
subLayouts = {}
subLayouts['LeftColumn'] = QGridLayout()
self.layout.addLayout(subLayouts['LeftColumn'],1)
# Buttons
self.buttons = {}
self.buttons['addVariable'] = QPushButton('>')
self.buttons['removeVariable'] = QPushButton('<')
self.buttons['Toolkit'] = QPushButton('Toolkit')
self.variables = QListWidget()
self.selectedVariables = QListWidget()
subLayouts['LeftColumn'].addWidget(self.variables, 7,0,4,1)
subLayouts['LeftColumn'].addWidget(self.selectedVariables, 7,1,4,1)
subLayouts['LeftColumn'].addWidget(self.buttons['addVariable'], 10,0,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['removeVariable'], 10,1,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['Toolkit'], 11,1,1,1)
names = ['apple', 'banana', 'Cherry']
self.variables.insertItems(0, names)
def setButtonConnections(self):
self.buttons['addVariable'].clicked.connect(self.add_variable)
self.buttons['Toolkit'].clicked.connect(self.show_new_window)
self.buttons['Toolkit'].clicked.connect(self.add_selected_variables)
def add_variable(self):
for item in self.variables.selectedItems():
self.selectedVariables.addItem(item.clone())
def show_new_window(self):
self.sw.show()
def add_selected_variables(self):
items = []
for i in range(self.selectedVariables.count()):
items.append(self.selectedVariables.item(i).clone())
self.tw.setItems(items)
if __name__ == "__main__":
import sys
app = QApplication([])
mw = MainWindow()
mw.show()
app.exec()
The main issue with your code is that secondWindowConnections is never called so the button actually does nothing. I corrected that and fixed a few other issues I found in my example below. I left out the bits where I made no changes and all the changes I did make I made inline notes explaining them:
class SecondWindow(QWidget):
def __init__(self):
super().__init__()
self.thirdWindow = None # dont initialize until neccessary
self.thirdWindowItems = []
self.layout = QGridLayout(self)
self.by = QLabel("By")
self.byVariables = QLineEdit()
self.byButton = QPushButton("...")
self.layout.addWidget(self.by, 1, 0)
self.layout.addWidget(self.byVariables, 2, 0)
self.layout.addWidget(self.byButton, 2, 1)
self.secondWindowConnections() # Run this to setup the
# signal for the third window.
def secondWindowConnections(self): # this had a typo
self.byButton.clicked.connect(self.show_third_window)
def show_third_window(self):
if self.thirdWindow is None: # if window has been created yet
self.thirdWindow = ThirdWindow() # create window
if not self.thirdWindow.isVisible(): # if window is showing
self.thirdWindow.show() # show window
self.thirdWindow.setItems(self.thirdWindowItems) # send items to window
def send_items(self, items): # this is to collect the variable that
self.thirdWindowItems = items # move to the third window
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Add a title
self.setWindowTitle("GUI Querying Program")
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.initUI()
self.setButtonConnections()
self.sw = None # dont initialize until neccessary.
def initUI(self):
subLayouts = {}
subLayouts['LeftColumn'] = QGridLayout()
self.layout.addLayout(subLayouts['LeftColumn'],1)
self.buttons = {}
self.buttons['addVariable'] = QPushButton('>')
self.buttons['removeVariable'] = QPushButton('<')
self.buttons['Toolkit'] = QPushButton('Toolkit')
self.variables = QListWidget()
self.selectedVariables = QListWidget()
subLayouts['LeftColumn'].addWidget(self.variables, 7,0,4,1)
subLayouts['LeftColumn'].addWidget(self.selectedVariables, 7,1,4,1)
subLayouts['LeftColumn'].addWidget(self.buttons['addVariable'], 10,0,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['removeVariable'], 10,1,1,1)
subLayouts['LeftColumn'].addWidget(self.buttons['Toolkit'], 11,1,1,1)
names = ['apple', 'banana', 'Cherry']
self.variables.insertItems(0, names)
def setButtonConnections(self):
self.buttons['addVariable'].clicked.connect(self.add_variable)
self.buttons['Toolkit'].clicked.connect(self.show_new_window)
# self.buttons['Toolkit'].clicked.connect(self.add_selected_variables)
# only use one connnect slot
def add_variable(self):
for item in self.variables.selectedItems():
self.selectedVariables.addItem(item.clone())
def show_new_window(self):
if self.sw is None: # check if window has been constructed
self.sw = SecondWindow() # construct window
if not self.sw.isVisible(): # If winow is not showing
self.sw.show() # show window
self.sw.send_items(self.add_selected_variables()) # send selected
# variables to second window
def add_selected_variables(self):
items = []
for i in range(self.selectedVariables.count()):
items.append(self.selectedVariables.item(i).clone())
# self.tw.setItems(items) ... self.tw doesnt exist so return them
return items
I tried change QTableWidgetItem font, and complete that.
But, In Editmode, not change font.
(PS. I shouldn't give same style, so i don't use qss style sheet)
Below code, If Input F1 key, Size up current cell font size.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class MainWindow(QMainWindow):
def __init__(self, **kwargs):
super().__init__()
self.init_main()
self.init_table()
self.resize(500,500)
self.show()
def init_main(self):
self.main_widget = QWidget()
self.main_layout = QHBoxLayout()
self.main_widget.setLayout(self.main_layout)
self.setCentralWidget(self.main_widget)
def init_table(self):
self.table = QTableWidget(5, 5, self)
self.table.resize(500, 500)
# init QTableWidgetItem in QTableWidget (5 x 5),
[[self.table.setItem(row, col,QTableWidgetItem("text")) for row in range(5)] for col in range(5)]
def keyPressEvent(self, e):
# If input F1, resize font-size in current item.
if e.key() == Qt.Key_F1:
cur = self.table.currentItem()
font = cur.font()
font.setPointSize(30)
cur.setFont(font)
if __name__ == "__main__":
app = QCoreApplication.instance()
if app is None:
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
Setting the font on an item just changes the font for that item, not for its editor.
What you need to do is to create an item delegate (which is an object that is responsible of showing items and provide interaction with the underlying model, including the appropriate editor).
Since setting the font on a QTableWidgetItem equals to set the Qt.FontRole of the index, you can easily access that from the createEditor() function, call the base implementation to get the editor that is going to be returned, and apply the font to it if a font is set.
class FontDelegate(QStyledItemDelegate):
def createEditor(self, parent, opt, index):
editor = super().createEditor(parent, opt, index)
font = index.data(Qt.FontRole)
if font is not None:
editor.setFont(font)
return editor
class MainWindow(QMainWindow):
# ...
def init_table(self):
self.table = QTableWidget(5, 5)
self.main_layout.addWidget(self.table)
[[self.table.setItem(row, col, QTableWidgetItem("text")) for row in range(5)] for col in range(5)]
self.table.setItemDelegate(FontDelegate(self.table))
# ...
Unrelated note: the table should be added to the layout (as I did in the above code), and not just created as a child of the main window.
I am trying to make a list box where a user can enter more items to the list. I have a list box set up with an add button. The add button opens up a user input box where it will direct the user to enter a value. However, I am have issue with passing on the value of user input to the add onto the list. Any suggestions would help. Below is my code:
List box
from input_box import *
class list_form(QtGui.QWidget):
def __init__(self,list_of_items,open_text,parent= None):
super(list_form, self).__init__()
global output_path
output_path = output_path_i
grid = QtGui.QGridLayout()
grid.setSpacing(10)
self.widget = QtGui.QWidget()
self.layout = QtGui.QGridLayout(self.widget)
open_message = QtGui.QLabel(open_text)
grid.addWidget(open_message,0,0,2,4)
self.lst = QtGui.QListWidget()
grid.addWidget(self.lst,3, 0,1,4)
for i in list_of_items:
self.lst.addItem(str(i))
self.setLayout(grid)
add = QtGui.QPushButton('Add')
grid.addWidget(add,50,0)
add.clicked.connect(self.add_button)
def add_button(self):
self.input_box = input_box()
self.input_box.setWindowTitle("Window 2")
self.input_box.show()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = list_form(list(xrange(100)),"List of Values")
window.setWindowTitle('Window 1')
window.show()
sip.setdestroyonexit(False)
sys.exit(app.exec_())
Input box
import sys
from PyQt4 import QtCore, QtGui
import sip
class input_box(QtGui.QWidget):
def __init__(self,parent= None):
super(input_box, self).__init__()
grid = QtGui.QGridLayout()
grid.setSpacing(10)
self.widget = QtGui.QWidget()
self.layout = QtGui.QGridLayout(self.widget)
open_message = QtGui.QLabel("Enter Value:")
grid.addWidget(open_message,0,0,2,3)
self.txt = QtGui.QLineEdit()
grid.addWidget(self.txt,2, 0,1,2)
self.setLayout(grid)
save = QtGui.QPushButton('Save')
grid.addWidget(save,50,0)
a = save.clicked.connect(self.save)
save.clicked.connect(self.close)
cancel = QtGui.QPushButton('Cancel')
grid.addWidget(cancel,50,1)
cancel.clicked.connect(self.close)
def save(self):
value = self.txt.text()
return value
If you want to get data from a window you should use a QDialog instead of a QWidget, connect the clicked signal of save and cancel to the accept and reject slot, respectively:
input_box.py
from PyQt4 import QtCore, QtGui
class Input_Box(QtGui.QDialog):
def __init__(self,parent= None):
super(Input_Box, self).__init__(parent)
open_message = QtGui.QLabel("Enter Value:")
self.txt = QtGui.QLineEdit()
save = QtGui.QPushButton('Save', clicked=self.accept)
cancel = QtGui.QPushButton('Cancel', clicked=self.reject)
grid = QtGui.QGridLayout(self)
grid.setSpacing(10)
grid.addWidget(open_message, 0, 0)
grid.addWidget(self.txt, 1, 0, 1, 2)
grid.addWidget(save, 2, 0)
grid.addWidget(cancel, 2, 1)
self.setFixedSize(self.sizeHint())
def save(self):
value = self.txt.text()
return value
Then you use the exec_() method that returns a code if it is called accept or reject, and according to that the data must be obtained and added. On the other hand, do not use global variables because they are a headache when debugging.
from PyQt4 import QtCore, QtGui
from input_box import Input_Box
class list_form(QtGui.QWidget):
def __init__(self,list_of_items,open_text,parent= None):
super(list_form, self).__init__()
open_message = QtGui.QLabel(open_text)
self.lst = QtGui.QListWidget()
self.lst.addItems([str(i) for i in list_of_items])
add = QtGui.QPushButton('Add', clicked=self.add_button)
grid = QtGui.QGridLayout(self)
grid.setSpacing(10)
grid.addWidget(open_message)
grid.addWidget(self.lst)
grid.addWidget(add)
#QtCore.pyqtSlot()
def add_button(self):
input_box = Input_Box()
input_box.setWindowTitle("Window 2")
if input_box.exec_() == QtGui.QDialog.Accepted:
val = input_box.save()
it = QtGui.QListWidgetItem(val)
self.lst.addItem(it)
self.lst.scrollToItem(it)
if __name__ == "__main__":
import sys
import sip
app = QtGui.QApplication(sys.argv)
window = list_form(list(range(100)),"List of Values")
window.setWindowTitle('Window 1')
window.show()
sip.setdestroyonexit(False)
sys.exit(app.exec_())
The advantage of using QDialog is the decoupling between the classes, for example there is no need to pass a QListWidget as the other answer suggests making it possible that you can use the same dialog for other purposes.
You need to arrange for the action taken when the save button is pressed to pass information back to the list widget. There's more than one way to do it, but just returning the data won't get it done.
Here's an example of the sort of thing that will work - though other approaches are possible.
Change the input_box constructor so it keeps a reference to the list widget which it expects:
class input_box(QtGui.QWidget):
def __init__(self, list_widget, parent= None):
super(input_box, self).__init__()
self.list_widget = list_widget
...
Change the call to the constructor to provide that information:
def add_button(self):
self.input_box = input_box(self.lst)
self.input_box.setWindowTitle("Window 2")
self.input_box.show()
And then use that information in the save method to add to the list widget:
def save(self):
value = self.txt.text()
self.list_widget.addItem(value)
Bingo!
An alternative approach could be to arrange for the input_box to emit a signal with the new value in it, and connect that to a slot on the list_form, or on the list_widget. Or in the input_box you could navigate via its parent to the list_widget. But I think mine is simple and straightforward.
According to the following table and the code which I constructed as an example, I require a proper code & table from which we can obtain the values of the 'Quantity' & 'Rate'(price) to be displayed as 'Subtotal' (Subtotal = Quantity * Rate). Its little bit confusing to understand the exact logic here.
here my code is given bellow:
from PyQt4 import QtGui, QtCore
import sys
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self. table = QtGui.QTableWidget(self)
self.table.move(10,70)
self.table.resize(500,300)
self.table_item = QtGui.QTableWidgetItem()
self.table.setRowCount(3)
self.table.verticalHeader().hide()
self.table.setColumnCount(6)
self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.fnt = self.table.font()
self.fnt.setPointSize(11)
self.table.setFont(self.fnt)
self.table.setHorizontalHeaderLabels(("S.no, Item Description,Qty,Rate(Rs:),Subtotal,"",").split(','))
self.table.setItem(0,0,QtGui.QTableWidgetItem("1"))
self.table.setItem(0,1, QtGui.QTableWidgetItem("Acne-aid Wash Facial Cleansing"))
self.table.setItem(0,3,QtGui.QTableWidgetItem("191.72"))
self.table.setItem(0,5,QtGui.QTableWidgetItem(""))
self.table.setItem(1,1,QtGui.QTableWidgetItem("Moisturizer"))
self.table.setItem(1,3,QtGui.QTableWidgetItem("90"))
self.table.setItem(1,5,QtGui.QTableWidgetItem(""))
self.table.setItem(1,0,QtGui.QTableWidgetItem("2"))
self.table.setItem(2,0,QtGui.QTableWidgetItem("3"))
self.table.setItem(2,1,QtGui.QTableWidgetItem("Brightening eye cream"))
self.table.setItem(2,3,QtGui.QTableWidgetItem("40"))
self.table.setItem(2,5,QtGui.QTableWidgetItem(""))
for x in range(0,4):
self.spin = QtGui.QSpinBox()
self.spin.setMinimum(1)
self.spin.setMaximum(50)
self.table.setCellWidget(x,2,self.spin)
for x in range(0,4):
self.btn = QtGui.QPushButton(self)
self.btn.setIcon(QtGui.QIcon("trash1.png"))
self.table.setCellWidget(x,5,self.btn)
self.setWindowTitle("To do app")
self.setGeometry(200,300,600,300)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The solution is to connect the valueChanged signal of the QSpinBox to any slot where the calculated is done, that signal sends the information of the current value but does not indicate the row to which the QSpinBox belongs. For this we use functool.partial to indicate the row (another option is to use a lambda function).
On the other hand I have improved your code, I see that you abuse self, for example in a for-loop the variables that are created inside must not be created using self. Also I have reduced the code with which you create the data.
import sys
from functools import partial
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self. table = QtGui.QTableWidget(3, 6, self)
self.table.setGeometry(10, 70, 500,300)
self.table.verticalHeader().hide()
self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
fnt = self.table.font()
fnt.setPointSize(11)
self.table.setFont(fnt)
self.table.setHorizontalHeaderLabels(("S.no, Item Description,Qty,Rate(Rs:),Subtotal,"",").split(','))
all_data = [("1", "Acne-aid Wash Facial Cleansing", 191.72, 0),
("2", "AMoisturizer", 90, 0),
("3", "Brightening eye cream", 40, 0)]
for r, row_data in enumerate(all_data):
for c, value in zip((0, 1, 3, 4), row_data):
it = QtGui.QTableWidgetItem(str(value))
self.table.setItem(r, c, it)
for r in range(self.table.rowCount()):
spin = QtGui.QSpinBox(minimum=0, maximum=50)
spin.valueChanged.connect(partial(self.calculateSubTotal, r))
self.table.setCellWidget(r, 2, spin)
btn = QtGui.QPushButton(icon=QtGui.QIcon("trash1.png"))
self.table.setCellWidget(r, 5, btn)
self.setWindowTitle("To do app")
self.setGeometry(200, 300, 600, 300)
self.show()
def calculateSubTotal(self, row, value):
rate = float(self.table.item(row, 3).text())
subtotal = value * rate
item_subtotal = self.table.item(row, 4)
if item_subtotal is None:
item_subtotal = QtGui.QTableWidgetItem()
self.table.setItem(row, 4, item_subtotal)
item_subtotal.setText(str(subtotal))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Here's my code. I'm trying to make it such that as you change the dropdown box, it will dynamically show more or less QLineEdits for input. This is just the latest iteration of testing
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit,
QInputDialog, QApplication, QComboBox, QFrame)
import numpy as np
class GUI(QWidget):
def __init__(self):
super().__init__()
self.initgui()
def initgui(self):
#
# Set up GUI
#
self.setGeometry(100, 100, 400, 400)
self.move(300, 300)
combobox = QComboBox(self)
for i in range(1, 10, 1):
combobox.addItem(str(i + 1))
combobox.activated[str].connect(self.comboboxchanged)
self.setWindowTitle("Testing Easy Setup")
self.show()
def comboboxchanged(self, text):
frame = QWidget(self)
frame.hide()
for num in range(0, int(text), 1):
QLineEdit(frame).move(60, num * 19)
frame.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = GUI()
sys.exit(app.exec_())
The problem is that when you pass a parent to a widget it is placed in the 0, 0 position with respect to the parent, in your case QFrame is on top of QComboBox since both are in the 0, 0 position. The proper thing is to use layouts. On the other hand you have to eliminate the widgets before adding new ones for it, we create a function that eliminates those items.
import sys
from PyQt5.QtWidgets import *
def clearLayout(lay):
while lay.count() > 0:
item = lay.takeAt(0)
widget = item.widget()
if widget:
widget.deleteLater()
del item
class GUI(QWidget):
def __init__(self):
super().__init__()
self.initgui()
def initgui(self):
lay = QHBoxLayout(self)
vlay1 = QVBoxLayout()
combobox = QComboBox(self)
combobox.addItems([str(i) for i in range(2, 11)])
vlay1.addWidget(combobox)
vlay1.addItem(QSpacerItem(20, 245, QSizePolicy.Minimum, QSizePolicy.Expanding))
self.vlay2 = QVBoxLayout()
lay.addLayout(vlay1)
lay.addLayout(self.vlay2)
self.comboboxchanged(combobox.currentText())
combobox.activated[str].connect(self.comboboxchanged)
self.setWindowTitle("Testing Easy Setup")
self.show()
def comboboxchanged(self, text):
clearLayout(self.vlay2)
for num in range(0, int(text)):
self.vlay2.addWidget(QLineEdit(self))
self.vlay2.addItem(QSpacerItem(20, 245, QSizePolicy.Minimum, QSizePolicy.Expanding))
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = GUI()
sys.exit(app.exec_())