2012-05-28 83 views
0
class Test(QtGui.QMainWindow): 
    def __init__(self): 
     super(Test, self).__init__() 

     self.initUI() 

    def initUI(self): 
     YDrive = QtGui.QAction(QtGui.QIcon('y.gif'), 'Exit', self) 
     SDrive = QtGui.QAction('S', self) 
     GDrive = QtGui.QAction('G', self) 
     AddDrive = QtGui.QAction('+', self) 
     YDrive.triggered.connect(self.setYDir) 

     SDrive.triggered.connect(self.setSDir) 
     GDrive.triggered.connect(self.setGDir) 

     self.toolbar = self.addToolBar('Exit') 
     self.toolbar.addAction(YDrive) 
     self.toolbar.addAction(SDrive) 
     self.toolbar.addAction(GDrive) 
     self.toolbar.addAction(AddDrive) 

     #btn1 = QtGui.QPushButton("Button 1", self) 
     #btn1.move(30, 50) 

     #btn2 = QtGui.QPushButton("Button 2", self) 
     #btn2.move(150, 50) 

     #btn1.clicked.connect(self.buttonClicked)    
     #btn2.clicked.connect(self.buttonClicked) 


     self.setGeometry(300, 300, 250, 150) 
     self.center() 
     self.setWindowTitle('Message box')  
     self.show() 

    def setYDir(self): 
     myInputs[1] = "Y" 
     print "myInputs[1] CHANGED to Y" 
     myWorkDrive = "Y:\\HoC_Jobs\\" 
     shows = self.listDirs(myWorkDrive) 

     for elements in shows: 
      btn1 = QtGui.QPushButton(elements, self) 
      btn1.move(30, 50) 
      btn1.clicked.connect(self.buttonClicked) 

我想在setYDir的最後一個循環中做的是爲列表中的每個元素創建一個按鈕。但是,它似乎並不正確。它不會更新按鈕,這取決於我在工具欄中單擊的按鈕。任何幫助?在每個循環創建一個PyQT窗口按鈕

回答

1

好吧,如果您不使用佈局將組件添加到父級窗口小部件,並且在父級上調用show後,您必須自己爲show孩子。

此外,所有的按鈕都是重疊的,所以你只會看到最後一個按鈕。在發佈源代碼時,將它剝離到運行它所需的最低限度總是好的。在這種情況下,看起來像這樣:

from PyQt4 import QtGui 
import os 

class Test(QtGui.QMainWindow): 
    def __init__(self): 
     super(Test, self).__init__() 

     self.initUI() 

    def initUI(self): 
     YDrive = QtGui.QAction("Y", self) 
     YDrive.triggered.connect(self.setYDir) 

     self.toolbar = self.addToolBar('Exit') 
     self.toolbar.addAction(YDrive) 

     self.setGeometry(300, 300, 250, 150) 
     self.setWindowTitle('Message box')  
     self.show() 

    def buttonClicked(self): 
     print "clicked" 

    def setYDir(self): 
     myWorkDrive = "/tmp" 
     shows = os.listdir(myWorkDrive) 
     i = 0 
     for elements in shows: 
      btn1 = QtGui.QPushButton(elements, self) 
      btn1.move(30, 50 + i) 
      i += 30 
      btn1.clicked.connect(self.buttonClicked) 
      btn1.show() 
     self.resize(self.width(), 50 + i) 


if __name__ == '__main__': 
    app = QtGui.QApplication([]) 
    t = Test() 
    t.show() 
    app.exec_()