PyQt:如何将QStandardItemModel中的QStandardItem连接到函数

时间:2017-03-01 10:13:24

标签: python pyqt qstandarditemmodel qstandarditem

我在PyQt中创建了一个应用程序,其中我有一个复选框列表,我使用QStandardItemModel和QStandardItem创建它,它完美地运行。我想将列表中的第一项连接到函数的“全选”复选框。此功能应该能够检查列表中的所有其他项目。我试图通过以下代码执行此操作:

    model = QStandardItemModel(list)  
    item = QStandardItem("Select all")
    model.appendRow(item)                  
    item.setCheckable(True)
    model.itemChanged.connect(state_changed)

    def state_changed(item):
         print ("Hello")

我已经从SQL查询的输出中向列表中添加了更多项目,我可以看到打印出“Hello”,而不管我单击哪个复选框。这是我的全部代码:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
def main():  
    db = QSqlDatabase.addDatabase("QODBC") 
    db.setHostName('LAPTOP-B79DRPA3')
    db.setDatabaseName('local')
    db.open()
    if (db.open()==False):     
      QMessageBox.critical(None, "Database Error",
                db.lastError().text())   

    query = QSqlQuery () 
    query.exec_  ("select id from [Sarah].[dbo].fraga")

    list = QListView()
    model = QStandardItemModel(list)  

    item = QStandardItem("Select all")
    model.appendRow(item)                  
    item.setCheckable(True)
    model.itemChanged.connect(state_changed)

    while (query.next()):
        item1 = QStandardItem(str(query.value(0)))
        model.appendRow(item1)                  
        item1.setCheckable(True)   

    list.setModel(model)
    list.show()
    return app.exec_()

def state_changed(item):
    print ("Hello")

if __name__ == '__main__':
    app  = QApplication(sys.argv)
    list = QListView()
    model = QStandardItemModel(list) 
    main()

如何确保仅在“全选”状态发生变化时才调用该函数?

1 个答案:

答案 0 :(得分:1)

连接到QAbstractItemModel.itemChanged信号,而不是连接到QAbstractItemView.clicked信号,该信号指定单击的索引。另外,建议不要命名变量list,因为它会干扰内置list

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
def main():
    db = QSqlDatabase.addDatabase("QODBC")
    db.setHostName('LAPTOP-B79DRPA3')
    db.setDatabaseName('local')
    db.open()
    if (db.open()==False):
      QMessageBox.critical(None, "Database Error",
                db.lastError().text())

    query = QSqlQuery ()
    query.exec_  ("select id from [Sarah].[dbo].fraga")

    list_view = QListView()
    model = QStandardItemModel(list_view)

    item = QStandardItem("Select all")
    model.appendRow(item)
    item.setCheckable(True)
    list_view.clicked.connect(state_changed)

    while (query.next()):
        item1 = QStandardItem(str(query.value(0)))
        model.appendRow(item1)
        item1.setCheckable(True)

    list_view.setModel(model)
    list_view.show()
    return app.exec_()

def state_changed(index):
    row = index.row()
    if row == 0:
        print ("Hello")

if __name__ == '__main__':
    app  = QApplication(sys.argv)
    list_view = QListView()
    model = QStandardItemModel(list)
    main()