Here it is sample program i want to update the my progress bar using with pyqt4.and i want to show th3 30% data saving and another 60% data processing.I am executing the my program it is aborting.Can any one please help me how to update the my progress bar.Thank you in advance.
Given below is my code:
import sys
import time
from pyface.qt import QtGui, QtCore
global X,Y
X= 5
Y= 4
import threading
class SaveWorker(QtCore.QObject):
progress_update = QtCore.Signal(int)
def save_file(self):
while True:
MyCustomWidget().updateProgressBar()
class Dialog(QtGui.QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
self.setStyleSheet("QDialog {background-color:black; color:white }")
self.label1 = QtGui.QLabel(
text="Please Wait...",
font=QtGui.QFont("Times", 20,weight=QtGui.QFont.Bold)
)
self.progress = QtGui.QProgressBar()
self.box = QtGui.QVBoxLayout()
self.label2 = QtGui.QLabel()
vbox = QtGui.QVBoxLayout(self)
vbox.addWidget(self.label1)
vbox.addLayout(self.box)
self.show_gif()
def show_gif(self):
self.progress = QtGui.QProgressBar()
self.progress.setRange(0,100)
self.box.addWidget(self.progress)
self.show()
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
self.worker = SaveWorker()
self.gif_dialog = Dialog()
self.worker.progress_update.connect(self.gif_dialog.show_gif)
thread = threading.Thread(target=self.worker.save_file)
thread.daemon = True
thread.start()
self.progressPer = 0
fileList = []
processes = []
_dataSavingPer = 30.0/(X*Y)
for i in range(X*Y):
name = 'file'+str(i+1) + ".txt"
fileList.append(name)
self.progressPer += _dataSavingPer
self.updateProgressBar(self.progressPer)
#updating the progress bar
_dataProcessPer = 60.0/(X*Y)
for file in fileList:
process = 'fileProcess'+str(i+1) + ".txt"
processes.append(process)
self.progressPer += _dataProcessPer
self.updateProgressBar(self.progressPer)
#Updating the progressPer
#how can i update these two values in to progressbar
def updateProgressBar(self,value):
self.gif_dialog.progress.setValue(value)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyCustomWidget()
sys.exit(app.exec_())
I do not understand what you tried when writing the following:
class SaveWorker(QtCore.QObject):
progress_update = QtCore.Signal(int)
def save_file(self):
while True:
MyCustomWidget().updateProgressBar()
updateProgressBar requires a value what value are you going through?, on the other hand when using MyCustomWidget() you are creating an object different from the one shown, and no MyCustomWidget object should be created in another thread.
What you have to do is move the heavy task to the save_file method since it will be executed in another thread:
import sys
import threading
from pyface.qt import QtGui, QtCore
X, Y = 5, 4
class SaveWorker(QtCore.QObject):
progressChanged = QtCore.Signal(int)
def save_file(self):
fileList = []
processes = []
_dataSavingPer = 30.0/(X*Y)
progress = 0
for i in range(X*Y):
name = 'file'+str(i+1) + ".txt"
fileList.append(name)
progress += _dataSavingPer
self.progressChanged.emit(progress)
_dataProcessPer = 60.0/(X*Y)
for file in fileList:
process = 'fileProcess'+str(i+1) + ".txt"
processes.append(process)
progress += _dataProcessPer
self.progressChanged.emit(progress)
class Dialog(QtGui.QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
self.setStyleSheet("QDialog {background-color:black; color:white }")
self.label1 = QtGui.QLabel(
text="Please Wait...",
font=QtGui.QFont("Times", 20,weight=QtGui.QFont.Bold)
)
self.progress = QtGui.QProgressBar()
self.box = QtGui.QVBoxLayout()
self.label2 = QtGui.QLabel()
vbox = QtGui.QVBoxLayout(self)
vbox.addWidget(self.label1)
vbox.addLayout(self.box)
self.show_gif()
def show_gif(self):
self.progress = QtGui.QProgressBar()
self.progress.setRange(0,100)
self.box.addWidget(self.progress)
self.show()
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
self.worker = SaveWorker()
self.gif_dialog = Dialog()
self.worker.progressChanged.connect(self.gif_dialog.progress.setValue)
thread = threading.Thread(target=self.worker.save_file)
thread.daemon = True
thread.start()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyCustomWidget()
sys.exit(app.exec_())
Related
I want to turn the dial on pyqt's GUI to change parameters while sounddevice's outputstream is processing, but the GUI freezes. I've tried everything I could find, and I've pieced together a bunch of code, but I'd like to know what the solution is.
I want to change the equalizer of the music being played in near real time by changing the parameters of the pedalboard that grants the equalizer.
import sys
import time
from PyQt5.QtCore import QObject, QThread, pyqtSignal
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import QSound
from pedalboard import *
import sounddevice as sd
import librosa
from threading import *
import threading
import soundfile as sf
def long_running_function(update_ui,board):
event = threading.Event()
try:
data, fs = sf.read('continue.wav', always_2d=True)
current_frame = 0
def callback(outdata, frames, time, status):
nonlocal current_frame
if status:
print(status)
chunksize = 2024
#print(chunksize, current_frame,len(data),frames)
outdata[:chunksize] = board(data[current_frame:current_frame + chunksize])
if chunksize < 2024:
outdata[chunksize:] = 0
raise sd.CallbackStop()
current_frame += chunksize
stream = sd.OutputStream(
samplerate=fs, blocksize=2024 , channels=data.shape[1],
callback=callback, finished_callback=event.set)
with stream:
event.wait()
except KeyboardInterrupt:
exit('\nInterrupted by user')
class Worker(QObject):
finished = pyqtSignal()
progress = pyqtSignal(int)
def __init__(self, main_window):
self.main_window = main_window
super(Worker, self).__init__(main_window)
def run(self):
long_running_function(self.update_progress,self.main_window.make_board())
self.finished.emit()
def update_progress(self, percent):
self.progress.emit(percent)
class MainWindow(QMainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.progress = QProgressBar()
self.button = QPushButton("Start")
self.dial = QDial()
self.init_ui()
self.qsound = None
self.qsound2 = None
self.effected_audio = None
self.audio = None
self.sr = None
self.dial.valueChanged.connect(self.make_board)
self.button.clicked.connect(self.execute)
self.show()
def init_ui(self):
self.setGeometry(100, 100, 250, 250)
layout = QVBoxLayout()
layout.addWidget(self.progress)
layout.addWidget(self.button)
layout.addWidget(self.dial)
self.setWindowTitle('Audio Player')
button_play = QPushButton("環境音を再生")
button_play2 = QPushButton("音楽と環境音を再生")
button_stop = QPushButton("Stop")
button_dialog = QPushButton("音楽を選択")
button_dialog2 = QPushButton("環境音を選択")
dial = QDial()
live = QPushButton("LIVE")
self.label = QLabel(self)
self.label2 = QLabel(self)
layout.addWidget(button_dialog)
layout.addWidget(button_dialog2)
layout.addWidget(button_play)
layout.addWidget(button_stop)
layout.addWidget(button_play2)
layout.addWidget(live)
layout.addWidget(self.dial)
layout.addWidget(self.label)
layout.addWidget(self.label2)
button_dialog.clicked.connect(self.button_openfile)
button_dialog2.clicked.connect(self.button_openfile2)
button_play.clicked.connect(self.button_play)
button_play2.clicked.connect(self.button_play2)
button_stop.clicked.connect(self.button_stop)
live.clicked.connect(self.start)
self.dial.valueChanged.connect(self.sliderMoved)
self.dial.valueChanged.connect(self.make_board)
self.dial.setMinimum(0)
self.dial.setMaximum(20)
self.dial.setValue(5)
w = QWidget()
w.setLayout(layout)
self.setCentralWidget(w)
def sliderMoved(self):
number = self.dial.value()
print(number)
return number
def make_board(self):
board = Pedalboard([
Compressor(ratio=10, threshold_db=-20),
Gain(gain_db=self.dial.value()),
Phaser(),
Reverb()
],sample_rate=44100)
return board
def button_play(self):
print("")
def button_play2(self):
if self.qsound is not None:
board = self.make_board(self.effects)
self.effected_audio = board(self.audio,self.sr)
sd.play(self.effected_audio)
self.qsound2.play()
def button_stop(self):
if self.qsound is not None:
sd.stop()
self.qsound2.stop()
def button_openfile(self):
filepath, _ = QFileDialog.getOpenFileName(self, 'Open file','c:\\',"Audio files (*.wav)")
filepath = os.path.abspath(filepath)
self.qsound = QSound(filepath)
self.filename = os.path.basename(filepath)
self.audio, self.sr = librosa.load(self.filename, sr=44100)
self.label.setText(self.filename)
self.label.adjustSize()
def button_openfile2(self):
filepath2, _ = QFileDialog.getOpenFileName(self, 'Open file','c:\\',"Audio files (*.wav)")
filepath2 = os.path.abspath(filepath2)
self.qsound2 = QSound(filepath2)
self.filename2 = os.path.basename(filepath2)
self.label2.setText(self.filename2)
self.label2.adjustSize()
def start(self):
self.thread.start()
def execute(self):
self.update_progress(0)
self.thread = QThread()
self.worker = Worker(self)
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.run)
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.worker.progress.connect(self.update_progress)
self.thread.start()
self.button.setEnabled(False)
def update_progress(self, progress):
self.progress.setValue(progress)
self.button.setEnabled(progress == 100)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
Qt Docs for moveToThread() say:
Changes the thread affinity for this
object and its children. The object
cannot be moved if it has a parent.
I cannot see where Worker instance gets started. Maybe you wanted to derive Worker from QThread, and call self.worker.start()?
OutputStream and the Qt GUI both have their own internal main loops which are responsible for handling their respective events. When you execute both on the same thread, one or the other might freeze.
Here in my sample program i want to display my gif upto my process is completed.After my process is completed automatically my gif will close.for that i used here threading function but i am not able to show gif.But i don't have any idea where i did mistake in this program,So can any one please check this program and please guide me.Thank you in advance.
Given below is my code:
import sys
from PyQt4 import QtGui
import os
class DialogThread(QtCore.QThread):
def __init__(self, interval=1):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
global savingDataFlag,dialog_gif
""" Method that runs forever """
while True:
if savingDataFlag == True:
dialog_gif.run()
print 'in saving data true loop'
else:
dialog_gif.close()
print 'in saving data false loop'
time.sleep(3)
class Dialog(QtGui.QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
self.setStyleSheet("QDialog {background-color:black; color:white }")
self.label1 = QtGui.QLabel(
text="Please Wait while It Is Processing The Data...",
font=QtGui.QFont("Times", 20,weight=QtGui.QFont.Bold)
)
self.label21 = QtGui.QLabel()
vbox1 = QtGui.QVBoxLayout(self)
vbox1.addWidget(self.label1)
vbox1.addWidget(self.label21)
self.resize(640, 480)
#QtCore.pyqtSlot()
def show_gif(self):
movie = QtGui.QMovie(
"./img/loading1.gif",
parent=self
)
self.label21.setMovie(movie)
movie.start()
self.exec_()class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
okButton = QtGui.QPushButton("Save")
cancelButton = QtGui.QPushButton("Cancel")
okButton.clicked.connect(self.save)
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
vbox = QtGui.QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle('Buttons')
self.show()
def save(self):
self.d1 = QtGui.QWidget()
self.form1 = QtGui.QFormLayout(self.d1)
self.name_file = QtGui.QLabel(("File Name:"))
self.line_edit1 = QtGui.QLineEdit()
self.saveBtn1 = QtGui.QPushButton(("Save"))
self.saveBtn1.clicked.connect(self.saveModelWidget)
self.canclebtn = QtGui.QPushButton(("Cancel"))
self.form1.addRow(self.name_file, self.line_edit1)
self.form1.addRow( self.canclebtn,self.saveBtn1)
self.d1.setWindowTitle("Enter Grids")
self.d1.setGeometry(450,300,500,100)
self.d1.show()
def saveModelWidget(self):
self.savefile()
def savefile(self):
self.d1.close()
self.save_text = self.line_edit1.text()
self.currFilePath = os.getcwd()
if self.save_text.endsWith(".csv"):
file_Name= self.save_text
with open(file_Name, 'w+')as f:
dir_path1 =os.getcwd()
save_filename = os.path.join(dir_path1,file_Name)
print "prrocess start"
# here some execution
# when i click the save button i want to display the gif file till to complete the process in save file
print "process ends"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You are using QThread with the threading module, and the QThread does not use it since it never starts it, instead you are using threading to execute the run () method. On the other hand overwriting the run method of QThread is a method but many limits many things, instead I will create a worker that will live in another thread. Another error is that movie is a local variable that will be deleted so it will not show, the solution is to pass it a parent. Considering the above the solution is:
import os
import sys
import threading
from PyQt4 import QtCore, QtGui
class SaveWorker(QtCore.QObject):
started = QtCore.pyqtSignal()
finished = QtCore.pyqtSignal()
#QtCore.pyqtSlot(str)
def save_file(self, filename):
self.started.emit()
for i in range(100000):
print(i)
with open(filename, 'w+')as f:
print(filename)
# some execution
self.finished.emit()
class GifDialog(QtGui.QDialog):
def __init__(self, parent = None):
super(GifDialog, self).__init__(parent)
self.setStyleSheet("QDialog {background-color:black; color:white }")
self.label1 = QtGui.QLabel(
text="Please Wait while It Is Processing The Data...",
font=QtGui.QFont("Times", 20,weight=QtGui.QFont.Bold)
)
self.label2 = QtGui.QLabel()
vbox = QtGui.QVBoxLayout(self)
vbox.addWidget(self.label1)
vbox.addWidget(self.label2)
#QtCore.pyqtSlot()
def show_gif(self):
movie = QtGui.QMovie(
"./img/loading1.gif",
parent=self
)
self.label2.setMovie(movie)
movie.start()
self.show()
class FormDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(FormDialog, self).__init__(parent)
self.setWindowTitle("Enter Grids")
self.line_edit = QtGui.QLineEdit()
self.savebtn = QtGui.QPushButton(
text="Save",
clicked=self.save
)
self.cancelbtn = QtGui.QPushButton("Cancel")
#self.savebtn.clicked.connect(self.saveModelWidget)
flay = QtGui.QFormLayout(self)
flay.addRow("File Name:", self.line_edit)
flay.addRow(self.cancelbtn, self.savebtn)
self.worker = SaveWorker()
self.gif_dialog = GifDialog(self)
self.worker.started.connect(self.gif_dialog.show_gif)
self.worker.finished.connect(self.close)
#QtCore.pyqtSlot()
def save(self):
filename = str(self.line_edit.text())
if filename.endswith(".csv"):
save_filename = os.path.join(os.getcwd(), filename)
thread = threading.Thread(target=self.worker.save_file, args=(save_filename,))
thread.daemon = True
thread.start()
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
okButton = QtGui.QPushButton(
text="Save",
clicked=self.on_clicked
)
cancelButton = QtGui.QPushButton("Cancel")
# okButton.clicked.connect(self.save)
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
vbox = QtGui.QVBoxLayout(self)
vbox.addStretch(1)
vbox.addLayout(hbox)
#QtCore.pyqtSlot()
def on_clicked(self):
dialog = FormDialog()
dialog.exec_()
def main():
app = QtGui.QApplication(sys.argv)
dialog = Example()
dialog.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I m trying to resize a table widget inside a QVBoxlayout which I further add as a row to a QFormlayout in pyqt
I m currently adding a QVboxlayout which contains a table widget inside it as a row in a Qformlayout.
And the main aim is to strecth the Table widget till the end of the application window that it acquires the left over space on the window
Using the below code -
class PGSearchDetails():
def __init__(self,parent=None):
self.widget_pgsd = QWidget()
self.layout_pgsd = QFormLayout()
self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
self.PG_Id = QLineEdit()
#rx = QRegExp("^\\D+[!,#,#,$,%,\^,&,*,(,),:,\",{,},?,<,>,|,+,-,~,]")
#rx = QRegExp(" (?!(#,#,$|%|\^|&|*|(|)|:|\"|{|}|?|<|>|\||+|-|~|!))[\\w]+")
str_rx = QRegExp("^[A-Za-z*]{20}(?!##$%^&*():\"\{\}?<>\|+-~!_-)")
adhr_rx = QRegExp("[A-Z0-9]{12}(?!##$%^&*():\"\{\}?<>\|+-~!_)")
val = QRegExpValidator(str_rx)
val3 = QRegExpValidator(adhr_rx)
self.PG_Id.setValidator(val3)
self.LastName = QLineEdit()
self.LastName.setValidator(val)
self.MobNum = QLineEdit()
qint_val = QIntValidator()
qint_val.setTop(10)
self.MobNum.setValidator(qint_val)
self.layout_pgsd.addRow("First Name",self.PG_Id)
self.layout_pgsd.addRow("Last Name",self.LastName)
self.layout_pgsd.addRow("Mobile Number",self.MobNum)
update_layout_pgsd = QHBoxLayout()
layout_test,table = dbv.Search_View(self.getT)
#layout_test.setGeometry(QRect(200,200,50,50))
#table.setMaximumHeight(800)
#table.setGeometry(200,200,200,200)
#table.setGeometry(1,1,1000,600)
table.resize(1000,600)
update_btn_pgsd = QPushButton('Update')
reset_btn_pgsd = QPushButton('Reset')
update_layout_pgsd.addWidget(update_btn_pgsd)
update_layout_pgsd.addWidget(reset_btn_pgsd)
self.layout_pgsd.addRow(update_layout_pgsd)
##Adding the Table Widget to FormLayot
self.layout_pgsd.addRow(layout_test)
update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
self.LastName))
#self.widget.setLayout(self.layout_pgsd)
def returnLayout(self):
return self.layout_pgsd
def returnWidget(self):
return self.widget_pgsd
def getT(self,linedit):
print("LE--->",linedit.text())
QtableWidget setup ---
def Search_View(self):
print("Inside Search_view")
central_widget = QWidget() # Create a central widget
db_layout = QVBoxLayout()
#col_count = len(self.pg_details.__dict__.keys())
col_count = 3
table = QTableWidget() # Create a table
#central_widget.setGeometry(200,200,150,150)
#table.maximumSize()
#db_layout.setMaximumSize(200)
db_layout.setGeometry(QRect(0,0,100,30))
db_layout.addWidget(table)
##Tried resizing the Table widget but nothing seems to works
table.resize(1000,600)
table.setGeometry(0,2,1000,600)
#central_widget.resize(central_widget.sizeHint())
#central_widget.setColumnWidth(1000,600)
#db_layout.addItem(update_layout)
central_widget.setLayout(db_layout)
print("Geometry H--->",table.geometry().height())
print("Geometry W--->",table.geometry().width())
print("Geometry X--->",table.geometry().x())
print("Geometry Y--->",table.geometry().y())
return central_widget,table
After the resize function, The table geometry changes to 1000,600 but on the screen it is not reflected. On the app screen it remains the same size everytime
Also find the entire code which contains the Tablayouts as well and Stacked widget for individual radio buttons
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.tab_widget = MainTabWindow()
self.setCentralWidget(self.tab_widget)
self.show()
class MainTabWindow(QTabWidget):
def __init__(self,parent=None):
super(MainTabWindow, self).__init__(parent)
self.init_ui()
def init_ui(self):
self.setWindowTitle('PyQt5 Tab Example')
self.tab1 = QWidget()
self.addTab(self.tab1,"Search")
self.PGSearchTab()
def PGSearchTab(self):
print("Search Tab First Tab")
self.central_layout = QVBoxLayout()
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack3 = QWidget()
self.stack_widget = QStackedWidget()
button_layout = QHBoxLayout()
radio_button_1 = QRadioButton("Search")
radio_button_2 = QRadioButton("Add")
radio_button_3 = QRadioButton("Update")
button_layout.addWidget(radio_button_1)
button_layout.addWidget(radio_button_2)
button_layout.addWidget(radio_button_3)
self.central_layout.addItem(button_layout)
self.stack_widget.addWidget(self.stack1)
self.stack_widget.addWidget(self.stack2)
self.stack_widget.addWidget(self.stack3)
self.central_layout.addWidget(self.stack_widget)
radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))
self.setTabText(0,"Search")
update_layout = QHBoxLayout()
update_layout.setAlignment(QtCore.Qt.AlignBottom)
update_btn = QPushButton('Update')
reset_btn = QPushButton('Reset')
update_layout.addWidget(update_btn)
update_layout.addWidget(reset_btn)
self.tab1.setLayout(self.central_layout)
def SelectButtonCheck(self,b):
if b.text() == "Search":
if b.isChecked():
print(b.text()+ "is selected")
self.obj_pgsd = pgsd.PGSearchDetails()
layout = self.obj_pgsd.returnLayout()
if self.stack1.layout() is None:
self.stack1.setLayout(layout)
self.stack_widget.setCurrentIndex(0)
def main():
application = QApplication(sys.argv)
main_window = MainTabWindow()
main_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main()
I do not seem to understand what is I m missing here
Any pointers would be appreciated.
Also find the working code to execute the above layout setup.
#!/usr/local/bin/python3
import sys
from PyQt5.QtWidgets import (QApplication, QWidget,QMainWindow,QLineEdit,QAction,
QLabel,QPushButton,QVBoxLayout,
QTabWidget,QFormLayout,QHBoxLayout,
QRadioButton,QCheckBox,QTextEdit,
QListView,QDialogButtonBox,QSizePolicy,QCalendarWidget)
from PyQt5 import QtCore
import PyQt5.Qt
from PyQt5.Qt import *
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtSql
from functools import partial
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.tab_widget = MainTabWindow()
self.setCentralWidget(self.tab_widget)
self.show()
class MainTabWindow(QTabWidget):
def __init__(self,parent=None):
super(MainTabWindow, self).__init__(parent)
self.init_ui()
def init_ui(self):
self.setWindowTitle('PyQt5 Tab Example')
self.tab1 = QWidget()
self.addTab(self.tab1,"Search")
self.PGSearchTab()
def PGSearchTab(self):
print("Search Tab First Tab")
self.central_layout = QVBoxLayout()
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack3 = QWidget()
self.stack_widget = QStackedWidget()
button_layout = QHBoxLayout()
radio_button_1 = QRadioButton("Search")
radio_button_2 = QRadioButton("Add")
radio_button_3 = QRadioButton("Update")
button_layout.addWidget(radio_button_1)
button_layout.addWidget(radio_button_2)
button_layout.addWidget(radio_button_3)
self.central_layout.addItem(button_layout)
self.stack_widget.addWidget(self.stack1)
self.stack_widget.addWidget(self.stack2)
self.stack_widget.addWidget(self.stack3)
self.central_layout.addWidget(self.stack_widget)
radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))
self.setTabText(0,"Search")
update_layout = QHBoxLayout()
update_layout.setAlignment(QtCore.Qt.AlignBottom)
update_btn = QPushButton('Update')
reset_btn = QPushButton('Reset')
update_layout.addWidget(update_btn)
update_layout.addWidget(reset_btn)
self.tab1.setLayout(self.central_layout)
def SelectButtonCheck(self,b):
if b.text() == "Search":
if b.isChecked():
print(b.text()+ "is selected")
self.obj_pgsd = PGSearchDetails()
layout = self.obj_pgsd.returnLayout()
if self.stack1.layout() is None:
self.stack1.setLayout(layout)
self.stack_widget.setCurrentIndex(0)
class PGSearchDetails():
def __init__(self,parent=None):
self.widget_pgsd = QWidget()
self.layout_pgsd = QFormLayout()
self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
self.PG_Id = QLineEdit()
#rx = QRegExp("^\\D+[!,#,#,$,%,\^,&,*,(,),:,\",{,},?,<,>,|,+,-,~,]")
#rx = QRegExp(" (?!(#,#,$|%|\^|&|*|(|)|:|\"|{|}|?|<|>|\||+|-|~|!))[\\w]+")
str_rx = QRegExp("^[A-Za-z*]{20}(?!##$%^&*():\"\{\}?<>\|+-~!_-)")
adhr_rx = QRegExp("[A-Z0-9]{12}(?!##$%^&*():\"\{\}?<>\|+-~!_)")
val = QRegExpValidator(str_rx)
val3 = QRegExpValidator(adhr_rx)
self.PG_Id.setValidator(val3)
self.LastName = QLineEdit()
self.LastName.setValidator(val)
self.MobNum = QLineEdit()
qint_val = QIntValidator()
qint_val.setTop(10)
self.MobNum.setValidator(qint_val)
self.layout_pgsd.addRow("First Name",self.PG_Id)
self.layout_pgsd.addRow("Last Name",self.LastName)
self.layout_pgsd.addRow("Mobile Number",self.MobNum)
update_layout_pgsd = QHBoxLayout()
layout_test,table = self.Search_View(self.getT)
#layout_test.setGeometry(QRect(200,200,50,50))
#table.setMaximumHeight(800)
#table.setGeometry(200,200,200,200)
#table.setGeometry(1,1,1000,600)
table.resize(1000,600)
update_btn_pgsd = QPushButton('Update')
reset_btn_pgsd = QPushButton('Reset')
update_layout_pgsd.addWidget(update_btn_pgsd)
update_layout_pgsd.addWidget(reset_btn_pgsd)
self.layout_pgsd.addRow(update_layout_pgsd)
##Adding the Table Widget to FormLayot
self.layout_pgsd.addRow(layout_test)
update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
self.LastName))
#self.widget.setLayout(self.layout_pgsd)
def returnLayout(self):
return self.layout_pgsd
def returnWidget(self):
return self.widget_pgsd
def getT(self,linedit):
print("LE--->",linedit.text())
def Search_View(self,text):
print("Inside Search_view")
central_widget = QWidget() # Create a central widget
db_layout = QVBoxLayout()
#col_count = len(self.pg_details.__dict__.keys())
col_count = 3
table = QTableWidget() # Create a table
#central_widget.setGeometry(200,200,150,150)
#table.maximumSize()
#db_layout.setMaximumSize(200)
db_layout.setGeometry(QRect(0,0,100,30))
db_layout.addWidget(table)
##Tried resizing the Table widget but nothing seems to works
table.resize(1000,600)
table.setGeometry(0,2,1000,600)
#central_widget.resize(central_widget.sizeHint())
#central_widget.setColumnWidth(1000,600)
#db_layout.addItem(update_layout)
central_widget.setLayout(db_layout)
print("Geometry H--->",table.geometry().height())
print("Geometry W--->",table.geometry().width())
print("Geometry X--->",table.geometry().x())
print("Geometry Y--->",table.geometry().y())
return central_widget,table
def SqlExec(self,text):
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName('localhost')
db.setDatabaseName('Test')
db.setUserName('root')
db.open()
query = QtSql.QSqlQuery()
select = "select * from Test.PG_Details where PG_Id=?"# where PG_Id = 1"
query.prepare(select)
indexes = range(3)
print("TEXT----->",text)
query.addBindValue(text)
#query.exec_(select)
query.exec_()
print("Sizze----",query.size())
row_count = query.size()
db.record('PG_Details')
col_list = []
for i in range(db.record('PG_Details').count()):
print("FIELD----->",db.record('PG_Details').field(i).name())
col_list.append(db.record('PG_Details').field(i).name())
db.close()
return query,row_count,col_list
def database(self,table,text,text2):
text = text.text()
query_result,row_count,col_list = self.SqlExec(text)
i = 0
table.setColumnCount(3) #Set three columns
table.setRowCount(row_count)
table.setHorizontalHeaderLabels(col_list)
while query_result.next():
#print(query_result.value(i))
result_row = [query_result.value(index) for index in range(query_result.record().count())]
#print("RR--->",result_row)
for idx,val in enumerate(result_row):
#print("IDX----->",idx)
table.setItem(i, idx, QTableWidgetItem(val))
i = i + 1
def main():
application = QApplication(sys.argv)
main_window = MainTabWindow()
main_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main()
The problem is that QFormLayout makes every time you add a widget using addRow () uses strech, the solution is to use a QVBoxLayout, and in that QVBoxLayout is to pass the QFormLayout and the layout_test.
class PGSearchDetails():
def __init__(self,parent=None):
self.widget_pgsd = QWidget()
self.layout = QVBoxLayout() # <---
self.layout_pgsd = QFormLayout()
self.layout.addLayout(self.layout_pgsd) # <---
self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
...
self.layout_pgsd.addRow(update_layout_pgsd)
##Adding the Table Widget to FormLayot
# self.layout_pgsd.addRow(layout_test)
self.layout.addWidget(layout_test) # <---
update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
self.LastName))
def returnLayout(self):
return self.layout # <---
I would like to ask how to make the text in QTextEdit scoll, to achieve an animational effect. The animational effect should be something like what in the video shows: https://www.youtube.com/watch?v=MyeuGdXv4XM
With PyQt I want to get this effect:
The text should be scolled automatically at a speed of 2 lines/second downwards, till it reaches the end and stops.
In my code below, when the button is clicked, the text is shown in QTextEdit-Widget. The text is very long, so that the scroll bar is shown.
My Problem:
I dont know how to make the animation effect. Thus I would like to ask your help to correct my code.
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import time
list_longText = [" long text 1 - auto scrolling " * 1000, " long text 2 - auto scrolling " * 2000]
class Worker(QObject):
finished = pyqtSignal()
strTxt = pyqtSignal(str)
def __init__(self, parent=None):
super(Worker, self).__init__(parent)
#pyqtSlot()
def onJob(self):
for i in range(2):
self.strTxt.emit(list_longText[i])
time.sleep(2)
class MyApp(QWidget):
def __init__(self):
super(MyApp, self).__init__()
self.setFixedSize(600, 400)
self.setObjectName("window")
self.initUI()
def initUI(self):
self.txt = QTextEdit("", self)
self.btn = QPushButton("Button", self)
self.btn.clicked.connect(self.start)
self.layout = QHBoxLayout(self)
self.layout.addWidget(self.txt)
self.layout.addWidget(self.btn)
self.setLayout(self.layout)
self.show()
def start(self):
self.thread = QThread()
self.obj = Worker()
self.obj.strTxt.connect(self.showText)
self.obj.moveToThread(self.thread)
self.obj.finished.connect(self.thread.quit)
self.thread.started.connect(self.obj.onJob)
self.thread.start()
def showText(self, str):
self.txt.setText("{}".format(str))
self.autoScroll()
def autoScroll(self):
vsb = self.txt.verticalScrollBar()
if vsb.value() <= vsb.maximum():
vsb.setValue(vsb.value() + 2)
time.sleep(1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
sys.exit(app.exec_())
Thanks very much for the help!
The task you want is not heavy, it is periodic so using a thread is inappropriate, for this task we can use QVariantAnimation.
The other part is to create a method that moves to a certain line of text for it we use QTextCursor next to findBlockByLineNumber() of QTextDocument.
And for the last one we must start moving to the last initial visible for it we use the cursorForPosition() method through the size of the viewport().
longText = "\n".join(["{}: long text - auto scrolling ".format(i) for i in range(100)])
class AnimationTextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.animation = QVariantAnimation(self)
self.animation.valueChanged.connect(self.move)
#pyqtSlot()
def startAnimation(self):
self.animation.stop()
lines_per_second = 2
self.moveToLine(0)
p = QPoint(self.viewport().width() - 1, self.viewport().height() - 1)
cursor = self.cursorForPosition(p)
self.animation.setStartValue(cursor.blockNumber())
self.animation.setEndValue(self.document().blockCount()-1)
self.animation.setDuration(self.animation.endValue()*1000/lines_per_second)
self.animation.start()
#pyqtSlot(QVariant)
def move(self, i):
cursor = QTextCursor(self.document().findBlockByLineNumber(i))
self.setTextCursor(cursor)
class MyApp(QWidget):
def __init__(self):
super(MyApp, self).__init__()
self.setFixedSize(600, 400)
self.txt = AnimationTextEdit(self)
self.btn = QPushButton("Start", self)
self.layout = QHBoxLayout(self)
self.layout.addWidget(self.txt)
self.layout.addWidget(self.btn)
self.txt.append(longText)
self.txt.move(0)
self.btn.clicked.connect(self.txt.startAnimation)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
Update:
if you want a continuous movement you must use verticalScrollBar():
longText = "\n".join(["{}: long text - auto scrolling ".format(i) for i in range(100)])
class AnimationTextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.animation = QVariantAnimation(self)
self.animation.valueChanged.connect(self.moveToLine)
#pyqtSlot()
def startAnimation(self):
self.animation.stop()
self.animation.setStartValue(0)
self.animation.setEndValue(self.verticalScrollBar().maximum())
self.animation.setDuration(self.animation.endValue()*4)
self.animation.start()
#pyqtSlot(QVariant)
def moveToLine(self, i):
self.verticalScrollBar().setValue(i)
class MyApp(QWidget):
def __init__(self):
super(MyApp, self).__init__()
self.setFixedSize(600, 400)
self.txt = AnimationTextEdit(self)
self.btn = QPushButton("Start", self)
self.layout = QHBoxLayout(self)
self.layout.addWidget(self.txt)
self.layout.addWidget(self.btn)
self.txt.append(longText)
self.txt.moveToLine(0)
self.btn.clicked.connect(self.txt.startAnimation)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
There will be as many Progress Bars created as there are entities in myList.
Clicking Ok button starts as many sub-processes as there are entities in myList.
Problem:
1. It seems there are way more sub-processes started than entities in myList.
2. Unable to update ProgressBar with a line(that's why it is commented):
pb.update_bar( self.pBars[each]['value'] )
import sys, os
from PyQt4 import QtCore, QtGui
import threading
import time
class PbWidget(QtGui.QProgressBar):
def __init__(self, parent=None, total=20):
super(PbWidget, self).__init__()
self.setMinimum(1)
self.setMaximum(total)
self._active = False
def update_bar(self, to_add_number):
while True:
time.sleep(0.01)
value = self.value() + to_add_number
self.setValue(value)
QtGui.qApp.processEvents()
if (not self._active or value >= self.maximum()):
break
self._active = False
def closeEvent(self, event):
self._active = False
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.myList = ['One','Two','Three','Four','Five','Six','Seven']
self.main_layout = QtGui.QVBoxLayout()
self.pBars={}
for each in self.myList:
pb=PbWidget(total=101)
self.main_layout.addWidget(pb)
self.pBars[each]={'pb':pb, 'name':each, 'value': 0}
ok_button = QtGui.QPushButton("Distribute")
ok_button.clicked.connect(self.OK)
self.main_layout.addWidget(ok_button)
central_widget = QtGui.QWidget()
central_widget.setLayout(self.main_layout)
self.setCentralWidget(central_widget)
def internalFunc(self, myEvent, each):
pb = self.pBars[each]['pb']
state=True
while state:
if self.pBars[each]['value']>=100: state=False
for i in range(12):
self.pBars[each]['value']+=10
print '\n\t ...Working on', each, self.pBars[each]['value'], '\n'
# pb.update_bar( self.pBars[each]['value'] )
time.sleep(0.5)
print "\n\t ProgressBar", each, 'has reached 100%. Its value =', self.pBars[each]['value'], '\n'
def OK(self):
for each in self.pBars:
self.myEvent=threading.Event()
self.c_thread=threading.Thread(target=self.internalFunc, args=(self.myEvent, each,))
self.c_thread.start()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.resize(480, 320)
window.show()
sys.exit(app.exec_())