2017-06-02 67 views
0

我在一個循環中創建多個小部件,並且它們都共享相同的回調。我的問題是確定觸發回調的小部件。當多個小部件共享相同的回調時識別源小部件

我試着給小部件的指數回調的這樣一個論點:

from PyQt5.QtCore import Qt 
from PyQt5.QtWidgets import QApplication, QSlider, QVBoxLayout, QWidget 
import sys 

class Foo(QWidget): 
    def __init__(self, parent=None): 
    super().__init__(parent) 

    self.sliders = [] 
    for n in range(10): 
     slider = QSlider(Qt.Horizontal) 
     slider.valueChanged.connect(lambda: self.on_slider(n)) 
     self.sliders.append(slider) 

    layout = QVBoxLayout() 
    for slider in self.sliders: 
     layout.addWidget(slider) 
    self.setLayout(layout) 

    def on_slider(self, n): 
    print(n) 


app = QApplication(sys.argv) 
gui = Foo() 
gui.show() 
sys.exit(app.exec()) 

但是這個打印9對於移動有滑。

回答

1

以獲得物體已經發射的信號有幾種形式,如:

  1. 必須先通過一個返回信號,然後將其它參數的參數。

slider.valueChanged.connect(lambda val, n=n: self.on_slider(val, n)) 

[...] 

def on_slider(self, val, n): 
    print(n, val) 

完整代碼:

class Foo(QWidget): 
    def __init__(self, parent=None): 
    super().__init__(parent) 

    self.sliders = [] 
    for n in range(10): 
     slider = QSlider(Qt.Horizontal) 
     slider.valueChanged.connect(lambda val, n=n: self.on_slider(val, n)) 
     self.sliders.append(slider) 

    layout = QVBoxLayout() 
    for slider in self.sliders: 
     layout.addWidget(slider) 
    self.setLayout(layout) 

    def on_slider(self, val, n): 
    print(n) 

2-另一種方法是使用objectNamesetObjectNamesender函數,返回發射信號的對象。


for n in range(10): 
     slider = QSlider(Qt.Horizontal) 
     slider.setObjectName(str(n)) 
     slider.valueChanged.connect(self.on_slider) 

[...] 

def on_slider(self, val): 
    print(self.sender().objectName(), val) 

完整代碼:

class Foo(QWidget): 
    def __init__(self, parent=None): 
    super().__init__(parent) 
    layout = QVBoxLayout(self) 

    for n in range(10): 
     slider = QSlider(Qt.Horizontal) 
     slider.setObjectName(str(n)) 
     slider.valueChanged.connect(self.on_slider) 
     layout.addWidget(slider) 

    def on_slider(self, val): 
    print(self.sender().objectName(), val) 
+0

再試一次請,我已校正碼 – eyllanesc

相關問題