2015-12-02 50 views
0

我試圖連接兩個不同類中的兩個方法。在所謂的「塔納」之類的,這是我的主要窗口,我有這樣的方法:已連接的類但未正確響應

def addChannel(self): 
    global channelCount 

    self.scrollLayout = QFormLayout() 

    self.canal = QwtPlot() 
    self.canal.setLayout(self.scrollLayout) 

    if channelCount <= 4:         
     self.splitter1.addWidget(self.canal) 
     channelCount += 1 
     print str(channelCount) 

在另一類,我有以下方法:

class QwtPlotList(QDialog): 
def __init__(self): 
    QDialog.__init__(self) 
    uic.loadUi("PropiedadesCanal.ui", self) 
    self.botonAdd.clicked.connect(self.addChannel_2) 

def addChannel_2(self): 
    global channelCount 
    self.botonAdd.clicked.connect(Ventana().addChannel) 
    if channelCount <= 4: 
     self.listWidget.addItem("Canal : " + str(channelCount)) 

什麼我正嘗試做的是當我按下按鈕「botonAdd」時,「addChannel_2」方法調用Ventana類中的「addChannel」方法。然後,創建一個QWidget(「self.canal」)。

這段代碼會發生什麼,當我按下「botonAdd」時,它會將項目放入listWidget中,但它不會創建QWidget。如果我創建了「QWidget」用工具欄中的按鈕,它doesn't在QListWidget

添加任何項目你可以看到這一切在這些圖片:

The "botonAdd" creates an item in the QListWidget but not a QWidget

Another button creates the Qwidget, but not the item in the QListWidget

希望你能幫助我。感謝您的時間和答案

回答

1

有幾個問題

從另一個類的類Ventana調用函數。你做什麼:

self.botonAdd.clicked.connect(Ventana().addChannel) 

Ventana()創建類Ventana的新實例。 按鈕botonAdd未連接到您的主窗口,而是 連接到您剛創建的另一個主窗口。這個新窗口 沒有顯示,並且被 垃圾回收器添加到addChannel_2的末尾(因爲您不保留對它的引用)。

要調用正確的addChannel,您需要參考您的實際主窗口。在Qt中,主窗口通常是其他窗口小部件的父窗口。您需要更改的QwtPlotList定義,以便它可以有一個父:

class QwtPlotList(QDialog): 
     def __init__(self,parent): 
     QDialog.__init__(self,parent) 

    #in main window Ventana 
    self.myDialog=QwtPlotList(self) 

然後你就可以調用任何Ventana方法QwtPlotList

#in QwtPlotList 
    self.parent().any_method() 

2.連接按鈕,點擊multitple功能。你做什麼:

self.botonAdd.clicked.connect(self.function1) 

    def function1(self): 
     self.botonAdd.clicked.connect(function2) 

每一次按鈕點擊,function1將被調用,並且將連接按鈕,點擊其他功能。這些連接是附加的。第一次單擊該按鈕時,將調用function1並將按鈕連接到function2。第二次調用function1function2,並且該按鈕連接到function2。第三次,function1function2又一次function2被稱爲等

你需要簡單地調用function2,無需連接按鈕:

def function1: 
    function2() 

使用全局變量:你應該避免,通常有更好的解決方案。
我知道你有兩個功能需要使用相同的變量channelCount。爲了避免全球性的,我會保持到channelCount一個參考QwtPlotList,並作爲參數傳遞在addChannel

def addChannel(channelCount): 
    channelCount+=1 
    return channelCount 

#QWtPlotList 
    #init 
    self.channelCount=3 

    def addChannel_2(self): 
    self.channelCount=addChannel(self.channelCount) 

我讓你弄清楚如何把一切融合在一起:)

+0

你好!謝謝你很多爲你的答案,我學到了新的東西。但我仍然有麻煩。現在我得到一個錯誤:「UnboundLocalError:局部變量'channelCount'在賦值之前引用」,如果我以簡單的方式解決該錯誤,它仍然不起作用。我編輯了這個問題,並且把我對你的答案做了什麼。對不起,如果我不能得到它。 –

+0

不要編輯您的問題。如果您遇到無法解決的新問題,請發佈新問題。 – Mel