2016-11-22 60 views
1

我是新來的Python和PyQt的/ pyside ...PyQt的獲取特定值ListWidget

我做customwidget類包括2標籤(標題&遞減),這是例子如用於增加以後Listwidget的...

這裏是完全乾淨的代碼(pyside瑪雅)

import PySide.QtCore as qc 
import PySide.QtGui as qg 

class CustomQWidget (qg.QWidget): 
    def __init__ (self, parent = None): 
     super(CustomQWidget, self).__init__(parent) 
     self.textQVBoxLayout = qg.QVBoxLayout() 
     self.titleLabel = qg.QLabel() 
     self.description = qg.QLabel() 
     self.textQVBoxLayout.addWidget(self.titleLabel) 
     self.textQVBoxLayout.addWidget(self.description) 
     self.setLayout(self.textQVBoxLayout) 
    def setTitle (self, text): 
     self.titleLabel.setText(text) 
    def setDescription (self, text): 
     self.description.setText(text) 

class example_ui(qg.QDialog): 
    def __init__(self): 
     qg.QDialog.__init__(self) 
     self.myQListWidget = qg.QListWidget(self) 
     self.myQListWidget.currentItemChanged.connect(self.getTitleValue) 
     self.myQListWidget.setGeometry(qc.QRect(0,0,200,300)) 
     # make instance customwidget item (just one)------ 
     instance_1 = CustomQWidget() 
     instance_1.setTitle('First title') 
     instance_1.setDescription('this is a sample desc') 
     myQListWidgetItem = qg.QListWidgetItem(self.myQListWidget) 
     myQListWidgetItem.setSizeHint(instance_1.sizeHint()) 
     self.myQListWidget.addItem(myQListWidgetItem) 
     self.myQListWidget.setItemWidget(myQListWidgetItem, instance_1) 
    def getTitleValue(self,val): 
     # i make assume something like below but didnt work 
     # print (self.myQListWidget.currentItem.titleLabel.text() 
     return 0 
dialog = example_ui() 
dialog.show() 

現在getTitleValue功能如何獲得標題和desc值當我改變選擇?

回答

1

你應該記住,列表項和相應的小部件是不一樣的。幸運的是,QListWidget對其進行跟蹤,並允許您訪問的,如果你提供的列表項控件顯示:

class example_ui(qg.QDialog): 
    def getTitleValue(self,val): 
     # parameter val is actually the same as self.myQListWidget.currentItem 
     selected_widget = self.myQListWidget.itemWidget(val) 
     print selected_widget.titleLabel.text()  
     return 0 

附註:我不得不爲了增加主循環對於要在所有執行的應用程序:

import sys # to give Qt access to parameters 
# ... class definitions etc. ... 
app = qg.QApplication(sys.argv) 
dialog = example_ui() 
dialog.show() 
exec_status = app.exec_() # main loop 
+0

感謝Sanyok您的時間,我現在明白了,注意:我在maya中運行代碼並且很好,如果要直接從python運行,那需要一個主循環(就像鍵入)。謝謝 –