2016-06-17 59 views
1

我目前正在使用PyQt 5和Python 3.5開發桌面應用程序。最近,我在嘗試將按鈕動態添加到佈局時遇到了一個問題。下面是我在做什麼:Python - 在PyQt中以圖形方式添加按鈕

for i in range(len(movieList)): 

     movies[i][0] = QtWidgets.QLabel("Title: " + movieList[i][0]) 
     movies[i][0].setGeometry(30, 50, 15, 20) 
     movies[i][0].setFont(self.movieTitleFont) 

     self.scrollLayout.addRow(movies[i][0]) 

     #If the lenght is 3 it means it has 2 available resolutions 
     if len(movieList[i]) == 3: 

      movies[i][1] = [QtWidgets.QPushButton(movieList[i][1][1], self), QtWidgets.QPushButton(movieList[i][2][1], self)] 

      movies[i][1][0].clicked.connect(lambda: self.downloadMovie(movieList[i], movieList[i][1][1])) 
      movies[i][1][0].setGeometry(0, 0, 10, 20) 

      movies[i][1][1].clicked.connect(lambda: self.downloadMovie(movieList[i], movieList[i][2][1])) 
      movies[i][1][1].setGeometry(10, 0, 10, 20) 

      self.scrollLayout.addRow(movies[i][1][0]) 
      self.scrollLayout.addRow(movies[i][1][1]) 

     else: 
      movies[i][1] = [QtWidgets.QPushButton(movieList[i][1][1], self)] 
      movies[i][1][0].clicked.connect(lambda: self.downloadMovie(movieList[i], movieList[i][1][1])) 
      movies[i][1][0].setGeometry(30, 50, 10, 20) 

      self.scrollLayout.addRow(movies[i][1][0]) 

我遇到的問題是,只要所有的電影在我的屏幕被加載,我嘗試按一個按鈕來下載該電影將只取一個值「我「存儲(clicked.connect),所以它會嘗試下載顯示的最後一部電影。我一直在努力尋找解決方法,但我還沒有找到方法。

回答

1

我想,如果你改變局部那麼一切都將正常工作

from functools import partial 
... 

for i in range(len(movieList)): 

     movies[i][0] = QtWidgets.QLabel("Title: " + movieList[i][0]) 
     movies[i][0].setGeometry(30, 50, 15, 20) 
     movies[i][0].setFont(self.movieTitleFont) 

     self.scrollLayout.addRow(movies[i][0]) 

     #If the lenght is 3 it means it has 2 available resolutions 
     if len(movieList[i]) == 3: 

      movies[i][1] = [QtWidgets.QPushButton(movieList[i][1][1], self), QtWidgets.QPushButton(movieList[i][2][1], self)] 

      movies[i][1][0].clicked.connect(partial(self.downloadMovie,movieList[i], movieList[i][1][1])) 
      movies[i][1][0].setGeometry(0, 0, 10, 20) 

      movies[i][1][1].clicked.connect(partial(self.downloadMovie,movieList[i], movieList[i][2][1])) 
      movies[i][1][1].setGeometry(10, 0, 10, 20) 

      self.scrollLayout.addRow(movies[i][1][0]) 
      self.scrollLayout.addRow(movies[i][1][1]) 

     else: 
      movies[i][1] = [QtWidgets.QPushButton(movieList[i][1][1], self)] 
      movies[i][1][0].clicked.connect(partial(self.downloadMovie,movieList[i], movieList[i][1][1])) 
      movies[i][1][0].setGeometry(30, 50, 10, 20) 

      self.scrollLayout.addRow(movies[i][1][0]) 
+0

非常感謝您!它工作得很好! – Guido

+0

沒問題,如果你想了解更多關於這次訪問,請點擊這裏http://stackoverflow.com/questions/11828410/differences-between-functools-partial-and-a-similar-lambda – Achayan

+0

太棒了!將檢查出來!謝謝 :) – Guido

相關問題