【发布时间】:2017-08-04 18:44:49
【问题描述】:
我一直在编写一个在服务器上运行远程脚本的程序。所以,我需要用一个栏显示进度,但是当我运行我的代码时,GUI 开始冻结。我使用过 QThread 和 SIGNAL 但很遗憾无法成功。
下面是我的代码;
class dumpThread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def sendEstablismentCommands(self, connection):
# Commands are sending sequently with proper delay-timers #
connection.sendShell("telnet localhost 21000")
time.sleep(0.5)
connection.sendShell("admin")
time.sleep(0.5)
connection.sendShell("admin")
time.sleep(0.5)
connection.sendShell("cd imdb")
time.sleep(0.5)
connection.sendShell("dump subscriber")
command = input('$ ')
def run(self):
# your logic here
# self.emit(QtCore.SIGNAL('THREAD_VALUE'), maxVal)
self.sendEstablismentCommands(connection)
class progressThread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
# your logic here
while 1:
maxVal = 100
self.emit(SIGNAL('PROGRESS'), maxVal)
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.connectButton.clicked.connect(self.connectToSESM)
def connectToSESM(self):
## Function called when pressing connect button, input are being taken from edit boxes. ##
## dumpThread() method has been designed for working thread seperate from GUI. ##
# Connection data are taken from "Edit Boxes"
# username has been set as hardcoded
### Values Should Be Defined As Global ###
username = "ntappadm"
password = self.ui.passwordEdit.text()
ipAddress = self.ui.ipEdit.text()
# Connection has been established through paramiko shell library
global connection
connection = pr.ssh(ipAddress, username, password)
connection.openShell()
pyqtRemoveInputHook() # For remove unnecessary items from console
global get_thread
get_thread = dumpThread() # Run thread - Dump Subscriber
self.progress_thread = progressThread()
self.progress_thread.start()
self.connect(self.progress_thread, SIGNAL('PROGRESS'), self.updateProgressBar)
get_thread.start()
def updateProgressBar(self, maxVal):
for i in range(maxVal):
self.ui.progressBar.setValue(self.ui.progressBar.value() + 1)
time.sleep(1)
maxVal = maxVal - 1
if maxVal == 0:
self.ui.progressBar.setValue(100)
def parseSubscriberList(self):
parsing = reParser()
def done(self):
QtGui.QMessageBox.information(self, "Done!", "Done fetching posts!")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
我希望看到 updateProgressBar 方法已通过 SIGNAL 调用,因此进程通过单独的线程。我找不到我失踪的地方。
感谢您的帮助
【问题讨论】:
-
如何在信号中定义整数?你能详细说明一下:progress_update = QtCore.Signal(int) 吗?
-
1.
progressThread的目的是什么?您有一个工作线程并且想要相应地更新您的 GUI,所以我看不到第三个线程的必要性。 2.为什么updateProgressBar中有一个循环?为什么每次迭代都减少maxVal?为什么你有一个time.sleep在那里?当然,如果你让它休眠,你的主线程会冻结。此外,每次调用updateProgressBar最终都会执行self.ui.progressBar.setValue(100),因为maxVal在最后一次迭代中为零。
标签: python user-interface pyqt signals-slots qthread