How to create activity indicator using pyQt4 designer for python - python-2.7

I'm learning about GUI python using pyQt4. I have function A in another file python. and I want to run in GUI file python that I extracted from file .ui (output of designer pyQt4). How to create activity indicator which is active when the function A is running? can I use progress bar (in pyQt4 designer) without know how many time for my function A running?
Thank you.
this is the function to call A in GUI .py:
def RunFunction():
import Kdtree
_dir = kdTreeOk.getNeighbor(float(radius)) #function 'A'
file = file_open('Summary.txt',_dir) # ignore, just file to save result of `A`
with file:
textOutput=file.read()
ui.result.setPlainText(textOutput)
#### button to run RunFunction in file GUI .py
ui._run.clicked.connect(RunFunction)

QProgressDialog is made for this purpose and generally called via QThread. Here's a (messy) basic example to show how this can work (without any threading). If you are calling this dialog from another window, just set parent as the calling window and you can read attributes in this dialog by calling self.parent.some_variable.
EDITED to work properly ;).
from PyQt4 import QtCore, QtGui
from time import sleep
import sys
class ProgressBarWidget(QtGui.QProgressDialog):
def __init__(self, parent=None, app=None):
super(ProgressBarWidget, self).__init__(parent)
self.app=app
self._allow_close = True
layout = QtGui.QVBoxLayout(self)
# Create a progress bar and a button and add them to the main layout
self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,100)
layout.addWidget(self.progressBar)
self.button = QtGui.QPushButton("Start", self)
layout.addWidget(self.button)
self.button.clicked.connect(self.onStart)
self.upload_count = 10
def onStart(self):
self.progressBar.setValue(0)
self.button.setText("Uploading...")
self.run()
def makeProgress(self, current_num, total_num, message = ''):
if total_num == current_num:
self.onFinished()
elif current_num == 0:
self.progressBar.setValue(0)
else:
multiplier = int(float(float(100) / float(total_num)))
c_times_m = current_num * multiplier
for i in xrange(c_times_m - int(self.progressBar.value())):
new_val = int(self.progressBar.value()) + 1
self.progressBar.setValue(new_val)
sleep(.01)
def onFinished(self):
# progress complete
self.progressBar.setRange(0,100)
for i in xrange(int(self.progressBar.value()),101):
self.progressBar.setValue(i)
self.button.setEnabled(True)
self.button.setText('Exit')
self.button.clicked.disconnect(self.onStart)
self.button.clicked.connect(self.close)
def run(self):
self._allow_close = False
self.button.setDisabled(True)
total = self.upload_count * 2
progress_meter = 0
downloaded = []
tests_to_upload = 10
for each in xrange(tests_to_upload):
sleep(0.15)
progress_meter += 1
self.makeProgress(progress_meter,total)
sleep(0.2)
progress_meter += 1
self.makeProgress(progress_meter, total)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = ProgressBarWidget(app=app)
window.resize(640, 480)
window.show()
sys.exit(app.exec_())

Related

Non-blocking print redirection to Tkinter text widget

I've been able to get print statements redirected to a Tkinter text widget based on the answer to this question. It describes a class to redirect stdout:
class TextRedirector(object):
def __init__(self, widget, tag="stdout"):
self.widget = widget
self.tag = tag
def write(self, str):
self.widget.configure(state="normal")
self.widget.insert("end", str, (self.tag,))
self.widget.configure(state="disabled")
Utilizing the TextRedirector class, I have the following code
import sys
import time
from tkinter import *
root = Tk()
t = Text(root, width = 20, height = 5)
t.grid()
old_stdout = sys.stdout
sys.stdout = TextRedirector(t)
for i in range(5):
print i + 1
time.sleep(1)
sys.stdout = old_stdout
However, this solution seems to be blocking (the text shows up all at once once the for-loop ends).
I have successfully put together a non-blocking solution using Popen and threading, but this isn't an ideal solution due to some unrelated constraints.
Is there a way to have the print statements show up in the text box in real-time?

PyQt4 label crashes when a function is called instead of using raw_input?

I boiled the original code down to a small section that still reproduces the issue. The below code works fine with action = raw_input('next action? ') instead of action = self.fake(). WHY??!! Specifically, the 'label' window will hang and crash using the class function, but will display the two overlaid images no problem using the user input. I cannot fathom how the two are impacting PyQt, especially since the changes are being made AFTER the image update.
import time
import sys
from PyQt4 import QtGui
class Basement(object):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
self.label = QtGui.QLabel()
def update_image(self):
self.im = QtGui.QImage('n-wall.png')
painter = QtGui.QPainter()
c_image = QtGui.QImage('bed.png')
painter.begin(self.im)
painter.drawImage(10, 10, c_image)
painter.end()
self.label.setPixmap(QtGui.QPixmap.fromImage(self.im))
self.label.show()
def fake(self):
return 'left'
def play_game(self):
### Update graphics / text
self.update_image()
### Decide action
action = self.fake()
#action = raw_input('next action? ')
time.sleep(5)
B = Basement()
B.play_game()

tkinter avoid GUI from freezing

I developed a simple Python application doing some stuff, then I decided to add a simple GUI using Tkinter.
The problem is that, while the I call a function called startprocess and begin doing stuff which is processor heavy and the window freezes.
I know it's a common problem and I've already read that I should use multithreads (very complicated, because the function updates the GUI too) or divide my code in different function, each one working for a little time. anyways is there any modification needed in below code to avoid GUI freezing?
import threading
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import os, datetime, sys, subprocess
import parselog_v1
# diplay messagebox window
def MessageBox(windowLable,msg):
messagebox.showinfo(windowLable, msg)
# check if Dir empty
def checkDirEmpty(work_path):
if os.path.isdir(work_path):
if not os.listdir(work_path):
print ("No Files found in directory")
MessageBox('Log Parser', 'No Files found in directory.')
else:
return True
# launch app in center of screen
def center_window(width=300, height=200):
# get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# calculate position x and y coordinates
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))
# application frame
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
self.master.title("Log Parser")
def createWidgets(self):
self.Run_Main = tk.Button(self)
self.Run_Main["text"] = "Browse for logs"
self.Run_Main["fg"] = "blue"
self.Run_Main["command"] = self.startProcess
self.Run_Main.pack(side='left',padx=0)
self.QUIT = tk.Button(self)
self.QUIT["text"] = "Quit!"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack(side='right',padx=5)
def startProcess(self):
global Src_foldername
Src_foldername = filedialog.askdirectory()
Src_foldername = Src_foldername.replace("/", "\\")
print("Source folder: " + Src_foldername)
if checkDirEmpty(Src_foldername):
# process logs
# multithread
print("Processing...")
self.refresh()
threading.Thread(target=parselog_v1.main(Src_foldername))
# scroll text inside application frame
class scrollTxtArea:
def __init__(self, root):
frame = tk.Frame(root)
frame.pack()
self.textPad(frame)
return
class IORedirector(object):
'''A general class for redirecting I/O to this Text widget.'''
def __init__(self, text_area):
self.text_area = text_area
class StdoutRedirector(IORedirector):
'''A class for redirecting stdout to this Text widget.'''
def textPad(self, frame):
# add a frame and put a text area into it
textPad = tk.Frame(frame)
self.text = tk.Text(textPad, height=21, width=68)
self.text.config()
# add a vertical scroll bar to the text area
scroll = tk.Scrollbar(textPad)
self.text.configure(yscrollcommand=scroll.set,background="black", foreground="green")
# pack everything
self.text.pack(side=tk.LEFT, pady=2)
scroll.pack(side=tk.RIGHT, fill=tk.Y)
textPad.pack(side=tk.TOP)
self.text.insert("end", "Begin by selecting log folder..." + "\n")
self.text.configure(state='disabled') # disable text editing
sys.stdout = (self) # to begin logging stdio to GUI
return
def write(self, txt):
self.text.configure(state='normal')
self.text.insert('end', txt)
self.text.configure(state='disabled')
root = tk.Tk()
root.resizable(width=False, height=False)
center_window(500, 300) # launch in center of screen
app = Application(master=root)
scrollFrame = scrollTxtArea(root)
app.mainloop()
root.destroy()
You use thread in wrong way.
First: target= needs function name without () and arguments.
You can assign arguments to args= (it have to be tuple even if you have only one argument)
threading.Thread(target=parselog_v1.main, args=(Src_foldername,) )
Now your code runs parselog_v1.main as normal function, waits for result and it will assign this result as function name to taget= - so you have something like this:
result = parselog_v1.main(Src_foldername)
threading.Thread(target=result)
It stops mainloop so it can't get mouse/keyboard events, refresh window, etc. so it looks like window freeze.
Second: after you create thread correctly you have to start it
my_thread = threading.Thread(target=parselog_v1.main, args=(Src_foldername,) )
my_thread.start()

Click signal in Pyqt4

I have a list of buttons which is shown to the user according to a particular number which the user enters.For e.g. If the user enters 2 then only 2 buttons will be shown.
The code that does this is here:
def set(self):
global seismicAttributeCount,lineEditlist
seismicAttributeCount=int(self.ui.lineEdit_23.text())
mygroupbox = QtGui.QGroupBox()
myform = QtGui.QFormLayout()
labellist = []
buttonList= []
for i in range(seismicAttributeCount):
lineEditlist.append(QtGui.QLineEdit())
buttonList.append(QtGui.QPushButton('Browse Attribute %i'%(i+1)))
myform.addRow(lineEditlist[i],buttonList[i])
mygroupbox.setLayout(myform)
self.ui.scrollArea_12.setWidget(mygroupbox)
self.ui.scrollArea_12.setWidgetResizable(True)
for i in range(seismicAttributeCount):
if buttonList[i].clicked.connect():
print i
I want to get the index of the button clicked. Any help would be appreciated.
You probably want to look into functools.partial. This allows you to connect an event with a method and a particular input. I've made here a minimal example of a GUI that does what you want
from PyQt4 import QtGui, QtCore
import sys
import functools
class test(QtGui.QWidget):
def __init__(self,parent=None):
self.widget=QtGui.QWidget.__init__(self, parent)
# Button to add buttons
self.btnAdd = QtGui.QPushButton('Add')
self.btnAdd.connect(self.btnAdd, QtCore.SIGNAL('clicked()'), self.btnAddPressed)
# Line edit for number of buttons
self.qleN = QtGui.QLineEdit(str(0))
# List to keep track of buttons
self.buttons=[]
# Layout
self.hbox = QtGui.QHBoxLayout()
self.hbox.addWidget(self.btnAdd)
self.hbox.addWidget(self.qleN)
self.setLayout(self.hbox)
self.show()
def btnAddPressed(self):
"""Adds number of buttons."""
# Get number of buttons to add
n=int(self.qleN.text())
self.buttons=[]
for i in range(n):
# Create new button
newBtn = QtGui.QPushButton(str(i))
self.buttons.append(newBtn)
# Connect
newBtn.clicked.connect(functools.partial(self.btnPressed,i))
self.hbox.addWidget(newBtn)
def btnPressed(self,idx):
"""Returns idx of btn."""
print idx
return idx
def main():
#Creating application
app = QtGui.QApplication(sys.argv)
main_win = test()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Note how I connect the button with a functools call and the index of the button.
By the way, next time, please make the effort and format your question properly.

MAXscript Listener can not run Pyside

Please help me !
I'm creating GUI by Python can run on the 3Ds Max, i heard someone said i have to use Pyside to make it. And everthing be fine until now.
This is my code :
import sys
from PySide import QtGui
from PySide.QtGui import *
from PySide.QtCore import *
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setMinimumHeight(660)
self.setMinimumWidth(700)
self.setMaximumHeight(660)
self.setMaximumWidth(700)
grid = QtGui.QGridLayout()
grid.addWidget(self.First(), 0,0,2,0)
self.setLayout(grid)
self.setWindowTitle("Library")
self.resize(700, 660)
def First(self):
groupBox = QtGui.QFrame()
groupBox.setMaximumWidth(230)
groupBox.setMaximumHeight(700)
lbRenderer = QtGui.QLabel("Renderer :",self)
lbFolders = QtGui.QLabel("Folders :",self)
cbRenderer = QtGui.QComboBox(self)
cbRenderer.addItem("Vray")
cbRenderer.addItem("Octane")
lvFolders = QtGui.QListView(self)
lvFolders.setMaximumWidth(220)
lvFolders.setMaximumHeight(500)
btnAddNewObject = QtGui.QPushButton('Add New Objects',self)
btnNewSet = QtGui.QPushButton('New Set',self)
vbox = QtGui.QGridLayout()
vbox.addWidget(lbRenderer,0,0)
vbox.addWidget(cbRenderer,0,1,1,3)
vbox.addWidget(lbFolders,2,0,1,4)
vbox.addWidget(lvFolders,3,0,1,4)
vbox.setColumnStretch(1, 1)
vbox.addWidget(btnAddNewObject,4,0,1,2)
vbox.addWidget(btnNewSet,4,3)
groupBox.setLayout(vbox)
return groupBox
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
clock = Window()
clock.show()
app.exec_()
I try another code same like my code , it run fine by "MAXScript Listener". But I dont know why when i try to run this, it dont appear anything(my GUI, or Alert is my code is not good).
First of all - you are initializing your script wrong, you call the 'initialize' function which returns #Success (meaning python initialized properly),
however you then just send in a string (which is the path to the file) and this does nothing.
What you have to use is:
python.ExecuteFile "C:\\Program Files\\Autodesk\\3ds Max 2015\\scripts\\Python\\yourPythonScript.py"
in maxscript listener\editor.
Autodesk documentation says:
Autodesk 3ds Max ships with a pre-built version of PySide 1.2
compatible with Python 2.7.3. This version includes the following
sub-set of modules:
QtCore
QtGui
QtNetwork
QtOpenGL
QtSql
QtSvg
QtTest
QtWebKit
QtXml
They have provided a simple sample script that you can run, save this in a python file, then execute it properly with the command mentioned in the beginning.
The code is here:
from PySide import QtGui
import MaxPlus
class _GCProtector(object):
widgets = []
def make_cylinder():
obj = MaxPlus.Factory.CreateGeomObject(MaxPlus.ClassIds.Cylinder)
obj.ParameterBlock.Radius.Value = 10.0
obj.ParameterBlock.Height.Value = 30.0
node = MaxPlus.Factory.CreateNode(obj)
time = MaxPlus.Core.GetCurrentTime()
MaxPlus.ViewportManager.RedrawViews(time)
return
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication([])
def main():
MaxPlus.FileManager.Reset(True)
w = QtGui.QWidget()
w.resize(250, 100)
w.setWindowTitle('Window')
_GCProtector.widgets.append(w)
w.show()
main_layout = QtGui.QVBoxLayout()
label = QtGui.QLabel("Click button to create a cylinder in the scene")
main_layout.addWidget(label)
cylinder_btn = QtGui.QPushButton("Cylinder")
main_layout.addWidget(cylinder_btn)
w.setLayout(main_layout)
cylinder_btn.clicked.connect(make_cylinder)
if __name__ == '__main__':
main()
They also mention this which is important:
Normally one creates a PySide application object in a script using
QtGui.QApplication(). However, in 3ds Max, there is already a PySide
application running, so you get a handle for that object like this:
QtGui.QApplication.instance()
Use that as a start script, and port your GUI items into that and it should get you up and running.
I tried to fix your code but anything happen, i dont know why.
First thing , i opened your code and run it in Pycharm but it can not run. But it totally run in Maxscript Listener, could you explain to me ?
Second i tried to fix your code. It's all the same, i can run it on Maxscript, but the content and function inside is disappear.
This is my code
from PySide import QtGui
import MaxPlus
class _GCProtector(object):
widgets = []
app = QtGui.QApplication.instance()
if not app:
app = QtGui.QApplication([])
def main():
MaxPlus.FileManager.Reset(True)
w = QtGui.QWidget()
w.setWindowTitle('Window')
_GCProtector.widgets.append(w)
w.show()
main_layout = QtGui.QGridLayout()
main_layout.addWidget(First(),0,0)
main_layout.addWidget(Second(),0,1)
w.setLayout(main_layout)
def First():
groupBox = QtGui.QFrame()
lbRenderer = QtGui.QLabel("Renderer :",self)
vbox = QtGui.QGridLayout()
vbox.addWidget(lbRenderer,0,0)
groupBox.setLayout(vbox)
return groupBox
def Second():
groupBox = QtGui.QFrame()
lbRenderer = QtGui.QLabel("Renderer :",self)
vbox = QtGui.QGridLayout()
vbox.addWidget(lbRenderer,0,0)
groupBox.setLayout(vbox)
return groupBox
if __name__ == '__main__':
main()
And this is the alert from Maxcript