2016-01-12 54 views
0

我需要ProgressBar小部件在my_app中,當我點擊pushButton時,我不能在def download (self)中調用def call_progressBar2(self,value1)。 任何人都可以幫助我嗎?如何從Python中的Main類調用GUI函數?

main.py

from g import Ui_MainWindow 
from PyQt4 import QtCore, QtGui 
import sys 
import time 
from b import classb 

class MainWindow(QtGui.QMainWindow): 
    def __init__(self, parent=None): 
     QtGui.QWidget.__init__(self, parent) 
     self.ui = Ui_MainWindow() 
     self.ui.setupUi(self) 
     instance_b=classb() 
     tvt= self.call_progressBar2(self) 
     QtCore.QObject.connect(self.ui.pushButton1, QtCore.SIGNAL("clicked()"), \ 
         lambda: instance_b.download(tvt))## I need help here. 


    def call_progressBar2(self,value1): 
     while True: 
      time.sleep(0.05) 
      value = self.ui.progressBar.value() + 1 
      self.ui.progressBar.setValue(value) 
      QtGui.qApp.processEvents() 
      if (not self.ui._active or 
       value >= self.progressBar.maximum()): 
       if value==value1: 
        break 
     self.ui._active = False    

if __name__ == "__main__": 
    app = QtGui.QApplication(sys.argv) 
    myapp = MainWindow() 
    myapp.show() 
    sys.exit(app.exec_()) 

b.py

import time 
from PyQt4 import QtCore, QtGui 

class classb (object): 
    def __init__(self, parent=None): 
     self.parent=parent 

#I need call def call_progressBar2() here. 
    def download(self): 
     from main import MainWindow 
     instance_m= MainWindow 
     print 'a' 
     instance_m.call_progressBar2(20) 
     print 'b' 
     instance_m.call_progressBar2(40) 
     print 'c' 
     instance_m.call_progressBar2(60) 
     print 'd' 
     instance_m.call_progressBar2(100) 

回答

1

而是在classb.download方法創建的MainWindow實例,只是把它作爲參數,在連接信號,這樣一來:

#tvt= self.call_progressBar2(self) #No need for tvt 
QtCore.QObject.connect(self.ui.pushButton1, QtCore.SIGNAL("clicked()"), \ 
         lambda: instance_b.download(self)) #self here is the MainWindow Instance 

然後在classb.download方法:

def download(self, main_window): 
    print 'a' 
    main_window.call_progressBar2(20) 
    print 'b' 
    main_window.call_progressBar2(40) 
    print 'c' 
    main_window.call_progressBar2(60) 
    print 'd' 
    main_window.call_progressBar2(100) 
+0

不錯......非常感謝您.... –

+0

您能幫我嗎?這裏http://stackoverflow.com/questions/34967007/how-can-i-make-new-thread-in-python –

1

你爲什麼不只是傳遞當前MainWindow實例您download功能,當您連接的信號?或者只是在連接信號之前立即將它傳遞給classb初始化程序?或者指定download,因此需要回撥,並且在連接信號時將MainWindow當前實例的call_progressBar2方法作爲回調傳遞?

+0

我想用(def call_progressBar2)作爲程序中的多功能,所以我現在需要在class_b中調用它。 –

+1

@JehanMazen我不明白「使用call_progressBar2作爲多功能」的意思。但無論如何:如果'classb.download'需要訪問調用的MainWindow實例的'call_progressBar2'方法,則必須傳遞調用的'MainWindow'實例或'call_progressBar'方法(請記住,在Python函數和方法也是對象)以某種方式下載。我提到了三種最明顯的方式,選擇適合你的方法。 –

+0

謝謝您的意見和建議 –