PyQt5 : How to use progress bar in PyQt5? - python

See my code and tell me how do I set progress bar to the -dollar()- function and progress bar start with doing the function and finished with it. see my code at the continue:
from PyQt5.QtWidgets import (QWidget,QApplication,QTextEdit,
QInputDialog,QPushButton,QVBoxLayout,QProgressBar)
import sys
class Tbx(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.btn = QPushButton('ClickMe',self)
self.btn.clicked.connect(self.dollar)
self.te = QTextEdit(self)
self.prgb = QProgressBar(self)#How to set this to doing something?
self.vbox.addWidget(self.te)
self.vbox.addWidget(self.btn)
self.vbox.addWidget(self.prgb)
self.setLayout(self.vbox)
self.setGeometry(300,300,400,250)
self.setWindowTitle('Application')
self.show()
def dollar(self):#Like doing this set progress bar to this
text_1_int , ok = QInputDialog.getInt(self,'HowMany?','Enter How Many dollar do you want ?')
if not ok:
return
current_lines = self.te.toPlainText().split('\n')
new_lines = list()
for dollar_counter in range(1,text_1_int+1):
word = '$'*dollar_counter
new_lines += [word + text for text in current_lines]
self.te.setPlainText('\n'.join(new_lines))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Tbx()
sys.exit(app.exec_())

You can set the maximum value of the progress control to the value entered in your input window and then simply use setValue to increase the progress bar, however, this will block the UI for very large calculations, so you might want to also move your method to a new thread and report progress to the UI using a signal, here is the full example:
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import (QWidget, QApplication, QTextEdit, QInputDialog, QPushButton, QVBoxLayout, QProgressBar)
import sys
class DollarCalculation(QThread):
reportProgress = pyqtSignal(int, list)
calculationFinished = pyqtSignal()
def __init__(self, numDollars, currentLines):
super().__init__()
self.numDollars = numDollars
self.currentLines = currentLines
def run(self) -> None:
for dollar_counter in range(1, self.numDollars + 1):
word = '$' * dollar_counter
self.reportProgress.emit(dollar_counter + 1, [word + text for text in self.currentLines])
self.calculationFinished.emit()
class Tbx(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.dollarCalculation = None
def initUI(self):
self.vbox = QVBoxLayout()
self.btn = QPushButton('ClickMe', self)
self.btn.clicked.connect(self.dollar)
self.te = QTextEdit(self)
self.prgb = QProgressBar(self)
self.vbox.addWidget(self.te)
self.vbox.addWidget(self.btn)
self.vbox.addWidget(self.prgb)
self.setLayout(self.vbox)
self.setGeometry(300, 300, 400, 250)
self.setWindowTitle('Application')
def dollar(self):
text_1_int, ok = QInputDialog.getInt(self, 'HowMany?', 'Enter How Many dollar do you want ?')
if not ok:
return
self.btn.setEnabled(False)
self.prgb.setMaximum(text_1_int + 1)
self.dollarCalculation = DollarCalculation(text_1_int, self.te.toPlainText().split('\n'))
self.dollarCalculation.reportProgress.connect(self.progress)
self.dollarCalculation.calculationFinished.connect(self.calculationFinished)
self.dollarCalculation.start()
def progress(self, value, newLines):
self.te.append('\n'.join(newLines))
self.prgb.setValue(value)
def calculationFinished(self):
self.btn.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Tbx()
ex.show()
sys.exit(app.exec_())

Related

PyQt GUI crashing while typing in LineEdit without any traceback error [duplicate]

This question already has answers here:
In PyQt, what is the best way to share data between the main window and a thread
(1 answer)
Background thread with QThread in PyQt
(7 answers)
Example of the right way to use QThread in PyQt?
(3 answers)
Closed 4 months ago.
I'm trying to make Typing speed test app in Pyqt, but it recently started crashing when I was inside QLineEdit. Sometimes it crashed instantly after I tried typing, sometimes only after tens of character were typed.
My code:
from PyQt5.QtWidgets import QWidget, QMainWindow, QApplication, QStackedWidget, QPushButton, QSizePolicy, QLabel, QLineEdit, QHBoxLayout, QVBoxLayout
from PyQt5.QtCore import *
import sys
import time
import random
import threading
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("Typing Speed Test App")
self.setMinimumSize(1280,720)
global stacked
stacked = QStackedWidget(self)
self.setCentralWidget(stacked)
stacked.addWidget(Menu())
stacked.addWidget(TS_Test())
stacked.addWidget(Statistics())
stacked.setCurrentIndex(1) # test only
class Menu(QWidget):
def __init__(self):
QWidget.__init__(self)
self.frameWidth = self.frameSize().width()
self.frameHeight = self.frameSize().height()
self.initUI()
def initUI(self):
self.button_test = QPushButton(self)
self.button_graph = QPushButton(self)
self.button_test.setFixedWidth(50)
self.button_test.clicked.connect(lambda: stacked.setCurrentIndex(1))
self.button_graph.clicked.connect(lambda: stacked.setCurrentIndex(2))
self.button_graph.clicked.connect(lambda: print(self.frameSize().width()))
self.button_test.move(self.frameSize().width()*50//100-50,200)
self.button_graph.move(200,230)
class TS_Test(QWidget):
def __init__(self):
QWidget.__init__(self)
f = open('paragraphs.txt').read()
self.sentences = f.split('BREAK\n')
self.sentence = random.choice(self.sentences)
self.sentence = self.sentence.strip('\n')
self.word = self.sentence.split()
self.setStyleSheet("QLabel{font-size: 15px;}")
self.initUI()
self.start_thread()
def initUI(self):
self.button_back = QPushButton(self)
self.button_back.clicked.connect(lambda: stacked.setCurrentIndex(0))
self.button_back.move(30,50)
self.lineEdit = QLineEdit()
self.label = QLabel()
self.accuracy_label = QLabel()
self.wpm_label = QLabel()
self.first_letter = self.sentence[0]
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.label)
self.layout.addWidget(self.lineEdit)
self.layout.addWidget(self.accuracy_label)
self.layout.addWidget(self.wpm_label)
self.label.setText(self.sentence)
self.layout.setContentsMargins(250,250,250,300)
self.setLayout(self.layout)
def start_thread(self):
self.t_start=threading.Thread(target=self.start)
self.t_start.start()
def start(self):
while True:
if len(self.lineEdit.text()) > 0:
if self.lineEdit.text()[0] == self.first_letter:
self.time_thread()
break
def time_thread(self):
print('start')
timer_start = time.perf_counter()
self.correct_char = 0
while True:
if (len(self.lineEdit.text()) == len(self.sentence)) and (self.lineEdit.text().split()[-1] == self.word[-1]):
self.written_word = self.lineEdit.text().split(' ')
timer_stop = time.perf_counter()
timer = timer_stop - timer_start
self.wpm = len(self.written_word) / timer * 60
for i in range(len(self.sentence)):
if self.lineEdit.text()[i] == self.sentence[i]:
self.correct_char += 1
self.accuracy = self.correct_char / len(self.sentence) * 100
print(f"Accuracy = {self.correct_char / len(self.sentence) * 100}")
print(f'WPM: {self.wpm:0.3f}')
self.accuracy_label.setText(f'Accuracy = {self.accuracy}%')
self.wpm_label.setText(f'WPM: {self.wpm:0.3f}')
break
class Statistics(QWidget):
def __init__(self):
QWidget.__init__(self)
self.initUI()
def initUI(self):
self.button_back = QPushButton(self)
self.button_back.clicked.connect(lambda: stacked.setCurrentIndex(0))
self.button_back.move(400,300)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainwin = MainWindow()
mainwin.show()
sys.exit(app.exec_())
I've tried doing try and except so that it can print me traceback error, but even that didn't print anything. I read somewhere that it might be because I'm using library threading instead of QThread, but I have no idea if that has something to do with it.
EDIT:
Content in paragraphs.txt:
This line serves as test.
BREAK
Sentence number one.
BREAK
Sentence number two.
BREAK
Line number three.

QPainter draw lines inside a QScrollArea

I raised a problem earlier on how to draw lines between widgets. and #eyllanesc solves it very well. But I faced another problem. I try to make the widget with QScrollarea. But the lines are not shown.
When using Widget it works fine with drawing lines, but seems QScrollArea need another paint_event. Don't know how to do that.
Can anyone help me to show lines with QScrollarea.
import functools
import sys
from PyQt5.QtCore import QEvent, QLine
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget, QScrollArea
class Drawer:
def __init__(self):
self._lines = []
#property
def lines(self):
return self._lines
#lines.setter
def lines(self, l):
self._lines = l[:]
self.update()
def paintEvent(self, event):
painter = QPainter(self)
for line in self.lines:
painter.drawLine(line)
class Example(QScrollArea, Drawer):
def __init__(self, parent=None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.AddButton = QPushButton("Add")
self.AddButton.clicked.connect(self.addbuttonwithline)
self.w = QWidget()
self.setWidget(self.w)
self.setWidgetResizable(True)
self.vbox = QVBoxLayout(self.w)
self.vbox.addWidget(self.AddButton)
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle("Buttons")
self.buttons = []
def addbuttonwithline(self):
button = QPushButton("delete")
button.clicked.connect(functools.partial(self.remove_button, button))
button.installEventFilter(self)
self.vbox.addWidget(button)
self.buttons.append(button)
self.recalculate_position()
def remove_button(self, button):
self.buttons.remove(button)
button.deleteLater()
self.recalculate_position()
def recalculate_position(self):
lines = []
for last_button, next_button in zip(self.buttons, self.buttons[1:]):
l = QLine(last_button.pos().x()+50, last_button.pos().y(), next_button.pos().x()+50, next_button.pos().y())
lines.append(l)
self.lines = lines
def eventFilter(self, o, e):
if e.type() == QEvent.Move and o in self.buttons:
self.recalculate_position()
return super().eventFilter(o, e)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
QScrollArea is designed to be a container so you should not paint over that item since the content covers it, instead it sets the painting in the content widget.
Based on my code from my previous answer then just change to:
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
w = QScrollArea(widgetResizable=True)
w.setWidget(ex)
w.show()
sys.exit(app.exec_())

Looking to fix size policy and how scrollArea shows in a tab

so I am trying to use PyQt5 to put a scroll area inside of a tab. Just playing around with a system that reads the serial port.
The issue I am having is that although I set a QVBoxLayout, the size does not seem to adjust to what I want it to be. It seems to be taking its minimum size and not adjusting.
I tried looking at the documentation on QSizePolicy on the website provided, but unfortunately it is all labeled as TODO.
https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtwidgets/qsizepolicy.html
I was wondering if anyone had some experience with this?
import sys
from PyQt5.QtWidgets import QMainWindow, QSizePolicy, QLabel, QGridLayout, QToolTip, QPlainTextEdit, QScrollArea, QApplication, QPushButton, QWidget, QAction, QTabWidget, QHBoxLayout, QVBoxLayout
from PyQt5.QtGui import *
from PyQt5.QtCore import pyqtSlot, QDateTime, Qt, pyqtSignal, QObject, QSize
import datetime
import serial
import serial.tools.list_ports
import threading
class FDSerial(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.connected = False
self.fd_line = ""
newAct = QAction(QIcon('icn/001-file.png'), 'New', self)
newAct.triggered.connect(self.init_sc)
self.toolbar = self.addToolBar('New')
self.toolbar.addAction(newAct)
openAct = QAction(QIcon('icn/002-folder.png'), 'Open', self)
self.toolbar.addAction(openAct)
connectAct = QAction(QIcon('icn/003-pendrive.png'), 'Connect', self)
connectAct.triggered.connect(self.find_port)
self.toolbar.addAction(connectAct)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
editMenu = menubar.addMenu('&Settings')
toolsMenu = menubar.addMenu('&Tools')
sessionMenu = menubar.addMenu('&Session')
helpMenu = menubar.addMenu('&Help')
self.statusBar().showMessage('Ready')
self.table_widget = LayoutWidgets(self)
self.setCentralWidget(self.table_widget)
self.setGeometry(400, 400, 800, 600)
self.setWindowTitle('FD Serial Demo')
self.show()
self.c = Communicate()
self.c.serialStuff.connect(lambda: self.table_widget.add_row(self.fd_line))
def init_sc(self):
self.ser = serial.Serial()
self.ser.baudrate = 115200
self.is_connected = False
self.tests_run = 0
self.port_found = False
def find_port(self):
if self.is_connected is False:
self.is_connected = True
else:
self.is_connected = False
for port in serial.tools.list_ports.comports():
if port.vid == 5824 and port.pid == 1155:
self.ser.port = str(port.device)
self.port_found = True
print("Found")
if self.port_found is False:
print("Not found")
x = threading.Thread(target=self.talk_module)
x.start()
def talk_module(self):
self.ser.open()
while self.is_connected is True:
self.fd_line = self.ser.readline().decode()
print(self.fd_line)
self.c.serialStuff.emit()
self.ser.close()
class Communicate(QObject):
serialStuff = pyqtSignal()
class LayoutWidgets(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.thisthat = 0
self.mySizePolicy = QSizePolicy()
self.mySizePolicy.setHorizontalStretch(1)
self.mySizePolicy.setVerticalStretch(1)
# self.mySizePolicy.setHeightForWidth(False)
# self.mySizePolicy.setHorizontalPolicy(QSizePolicy.Maximum)
# self.mySizePolicy.setVerticalPolicy(QSizePolicy.Maximum)
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.addTab(self.tab1, "Serial CANFD Interface")
self.tabs.addTab(self.tab2, "Data Visualizer")
self.tab1.layout = QVBoxLayout()
self.tab2.layout = QVBoxLayout()
self.scrollArea = QScrollArea(self.tab1)
self.scrollArea.setWidgetResizable(True)
# self.widget = QWidget()
# self.scrollArea.setWidget(self.widget)
self.layout_SArea = QVBoxLayout(self.scrollArea)
self.layout_SArea.setSpacing(0)
self.tab1.layout.addWidget(self.scrollArea)
self.scrollArea.setSizePolicy(self.mySizePolicy)
self.scrollArea.setStyleSheet("background-color:'#d3f3c8'")
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
self.qtextbig = QPlainTextEdit()
self.qtextbig.setSizePolicy(self.mySizePolicy)
self.qtextbig.setReadOnly(False)
self.layout_SArea.addWidget(self.qtextbig)
def add_row(self, row):
self.this = str(row)
self.this2 = str(datetime.datetime.now().time())
self.thisthat = self.thisthat + 1
self.qtextbig.appendPlainText(self.this)
self.qtextbig.appendPlainText(self.this2)
self.qtextbig.appendPlainText(str(self.thisthat))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = FDSerial()
sys.exit(app.exec_())
Here is how the GUI looks right now. The scroll are is way too small! It is in green.
I am looking for the scroll area to take the whole tab size, and then adjust as I adjust the window size. Would appreciate any pointers.
Thanks!
The problem has nothing to do with the QSizePolicy, they are not really necessary. The problem is that you are not using layouts. I think that using the following instruction:
self.tab1.layout = QVBoxLayout()
self.tab2.layout = QVBoxLayout()
add a layout to each tab, but it is only pointing out that there is a new property called layout that takes the value of the QVBoxLayout and that deletes the reference to the layout method of the tab, ie it only deletes the access to the tab1.layout() method, and doing it is a bad practice.
Considering the above I have used the following code:
# ...
class LayoutWidgets(QWidget):
def __init__(self, parent=None):
super(QWidget, self).__init__(parent)
layout = QVBoxLayout(self)
self.thisthat = 0
self.tabs = QTabWidget()
layout.addWidget(self.tabs)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.addTab(self.tab1, "Serial CANFD Interface")
self.tabs.addTab(self.tab2, "Data Visualizer")
lay = QVBoxLayout(self.tab1)
self.scrollArea = QScrollArea(widgetResizable=True)
self.scrollArea.setStyleSheet("background-color:'#d3f3c8'")
lay.addWidget(self.scrollArea)
layout_SArea = QVBoxLayout(self.scrollArea)
self.qtextbig = QPlainTextEdit(readOnly=False)
layout_SArea.addWidget(self.qtextbig)
def add_row(self, row):
self.this = str(row)
self.this2 = str(datetime.datetime.now().time())
self.thisthat = self.thisthat + 1
self.qtextbig.appendPlainText(self.this)
self.qtextbig.appendPlainText(self.this2)
self.qtextbig.appendPlainText(str(self.thisthat))
# ...

Updating slider value constantly crashes program

Maybe I'm doing this completely wrong here, I'm trying to make the "timeline" for an mp3 player. Everything works and I've tried to set the slider to one value and it was fine. My problem is when I try updating the timeline as it keeps on freezing the program and it doesn't unfreeze. Here's my code, I commented out where to start looking at in terms of where I'm having trouble in:
import sys
from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton,
QSlider
import vlc
player = vlc.MediaPlayer("/songs/Immigrant Song.mp3")
class window(QMainWindow):
def __init__(self):
super(window, self).__init__()
self.setGeometry(50, 50, 400, 200)
self.setWindowTitle('SlugPlayer')
#self.setWindowIcon(QIcon('pic.png'))
self.home()
def home(self):
playing = 0
btn = QPushButton('quit', self)
btn.clicked.connect(self.close_application)
btn.resize(btn.sizeHint()) #set to acceptable size automatic
btn.move(0, 0)
playbtn = QPushButton('Play', self)
# playbtn.clicked.connect(self.update_bar, playing)
playbtn.clicked.connect(self.play_music, playing)
playbtn.resize(playbtn.sizeHint())
playbtn.move(100, 0)
psebtn = QPushButton('Pause', self)
psebtn.clicked.connect(self.pause_music, playing)
psebtn.resize(psebtn.sizeHint())
psebtn.move(200, 0)
stopbtn = QPushButton('Stop', self)
stopbtn.clicked.connect(self.stop_music, playing)
stopbtn.resize(stopbtn.sizeHint())
stopbtn.move(300, 0)
self.sl = QSlider(Qt.Horizontal, self)
self.sl.setFocusPolicy(Qt.NoFocus)
self.sl.setGeometry(30, 50, 300, 20)
self.sl.setMinimum(0)
self.sl.setMaximum(100)
self.sl.setValue(0)
self.sl.move(50, 100)
# self.sl.valueChanged[int].connect(self.print_value)
self.show()
def close_application(self):
sys.exit()
#here is where I'm trying to update the bar
def play_music(self, playing):
player.play()
playing = 1
while playing == 1:
self.update_bar(playing)
def pause_music(self, playing):
player.pause()
playing = 0
def stop_music(self, playing):
player.stop()
playing = 0
def print_value(self, value):
print(value)
#function to update the bar (converts to an int)
def update_bar(self, playing):
self.sl.setValue(int(player.get_position() * 100))
def run():
app = QApplication(sys.argv)
Gui = window()
sys.exit(app.exec_())
run()
An infinite loop like while playing == 1 freezes the GUI since it does not allow you to do other tasks, in these cases it is better to use a QTimer. Going a little further to the bottom of the problem I have implemented a class that is in charge of managing the player by sending signals when necessary.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import vlc
class VLCManager(QtCore.QObject):
durationChanged = QtCore.pyqtSignal(int)
positionChanged = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(VLCManager, self).__init__(parent)
self._player = vlc.MediaPlayer()
self._timer = QtCore.QTimer(self, interval=100, timeout=self.update_values)
def setFileName(self, filename):
self._player = vlc.MediaPlayer(filename)
def position(self):
self.durationChanged.emit(self.duration())
return self._player.get_time()
def setPosition(self, time):
if self.position() != time:
self._player.set_time(time)
#QtCore.pyqtSlot()
def update_values(self):
self.positionChanged.emit(self.position())
def duration(self):
return self._player.get_length()
#QtCore.pyqtSlot()
def play(self):
self._player.play()
self.update_values()
self._timer.start()
#QtCore.pyqtSlot()
def pause(self):
self._player.pause()
self.update_values()
self._timer.stop()
#QtCore.pyqtSlot()
def stop(self):
self._player.stop()
self.update_values()
self._timer.stop()
class window(QtWidgets.QMainWindow):
def __init__(self):
super(window, self).__init__()
self._manager = VLCManager(self)
self._manager.setFileName("/songs/Immigrant Song.mp3")
self.setWindowTitle('SlugPlayer')
self.home()
def home(self):
quitbtn = QtWidgets.QPushButton('quit')
quitbtn.clicked.connect(self.close)
playbtn = QtWidgets.QPushButton('Play')
playbtn.clicked.connect(self._manager.play)
psebtn = QtWidgets.QPushButton('Pause', self)
psebtn.clicked.connect(self._manager.pause)
stopbtn = QtWidgets.QPushButton('Stop', self)
stopbtn.clicked.connect(self._manager.stop)
self.sl = QtWidgets.QSlider(orientation=QtCore.Qt.Horizontal)
self.sl.setFocusPolicy(QtCore.Qt.NoFocus)
self._manager.durationChanged.connect(self.sl.setMaximum)
self._manager.positionChanged.connect(self.sl.setValue)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
hlay = QtWidgets.QHBoxLayout()
for b in (quitbtn, playbtn, psebtn, stopbtn, ):
hlay.addWidget(b)
lay.addLayout(hlay)
lay.addWidget(self.sl)
self.sl.valueChanged[int].connect(self._manager.setPosition)
self.show()
def run():
app = QtWidgets.QApplication(sys.argv)
Gui = window()
sys.exit(app.exec_())
run()

How can I dynamically add/remove elements in an element?

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_())

Categories

Resources