Getting data from selected item in QListView

后端 未结 3 549
北恋
北恋 2021-01-03 12:45

I populate a QListView with QSqlTableModel.

  projectModel = QSqlTableModel()
  projectModel.setTable(\"project\")
  projectModel.select()

  projectView = Q         


        
3条回答
  •  迷失自我
    2021-01-03 13:44

    In my QListView I'm displaying column 1, so only the names. Then I have 1 item selected. How can I retrieve that item's id and color?

    Please check the following example. You can add a function to the "clicked" slot of QListView. Then get the which row is selected.

    from PyQt4.QtSql import QSqlDatabase,QSqlTableModel
    from PyQt4.QtGui import QListView,QApplication
    import sys
    
    def listclicked(index):
        row = index.row()
        print "id = %s" % projectModel.record(row).field(0).value().toString()
        print "country = %s" % projectModel.record(row).field(2).value().toString()
    
    app = QApplication(sys.argv)
    
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName("sqlitedb.rdb")
    db.open()
    
    projectModel = QSqlTableModel()
    projectModel.setTable("info")
    projectModel.select()
    
    projectView = QListView()
    projectView.setModel(projectModel)
    projectView.setModelColumn(1)
    projectView.clicked.connect(listclicked)
    projectView.show()
    
    app.exec_()
    

提交回复
热议问题