从tableView mod打印单击行的数据

2024-04-19 19:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个对话框:

class classsearchresult(QDialog, Ui_Dialog):
def __init__(self, parent=None):
    QDialog.__init__(self, parent)
    self.setupUi(self)
    self.tableView.setShowGrid(False)
    self.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
    vh = self.tableView.verticalHeader()
    vh.setVisible(False)
    hh = self.tableView.horizontalHeader()
    hh.setVisible(False)
    hh.setStretchLastSection(True)
    self.pushButton_2.clicked.connect(self.close)
    db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('formuladatabase')
    db.open()
    self.projectModel = QtSql.QSqlQueryModel(self)
    self.projectModel.setQuery("select rowid, Name, Surname from search",db)
    self.tableView.setModel(self.projectModel)
    self.tableView.clicked.connect(self.handlebutton)

tableview工作得很好只需打印点击的行

^{pr2}$

我试了一段时间,但还是搞不懂这个。在


Tags: selffalsedbinithhconnectparent对话框
2条回答

请注意:我注意到你标记了PyQt5,但是那里的文档不是很好,我很有信心我在这里所说的仍然适用(来自PyQt4)。在

看起来好像您假设rows将包含来自您的查询的数据,但它没有。selectedRows(),selectedColumns,selectedIndexes()(本文记录:http://pyqt.sourceforge.net/Docs/PyQt4/qitemselectionmodel.html#selectedRows)所有返回类型list-of-QModelIndex,基本上是索引。。不是数据。在

list-of-QModelIndex QItemSelectionModel.selectedRows (self, int column = 0)

Returns the indexes in the given column for the rows where all columns are selected.

我认为使用selectedIndex比较容易

list-of-QModelIndex QItemSelectionModel.selectedIndexes (self)

Returns a list of all selected model item indexes. The list contains no duplicates, and is not sorted.

为了得到数据,型号记录值()返回一个QVariant,您必须将其转换为正确的类型才能进行打印。所以,在你的情况下:

rows = self.tableView.selectionModel().selectedIndexes()
print self.projectModel.record(rows[0].row()).value("rowid").toInt()
print self.projectModel.record(rows[0].row()).value("Name").toString()
print self.projectModel.record(rows[0].row()).value("Surname").toString()

row[0].row()正在访问返回的“QModelIndex列表”类型的元素0,QModelIndex(http://pyqt.sourceforge.net/Docs/PyQt4/qmodelindex.html#details)有一个row()方法,该方法返回行的索引。考虑到您的设置方式,“list of QModelIndex”列表应该始终是单个元素列表(您用“clicked”信号连接它),所以行[0]应该返回正确的元素。在

更多信息请参见此处: http://ftp.ics.uci.edu/pub/centos0/ics-custom-build/BUILD/PyQt-x11-gpl-4.7.2/doc/html/qtsql.html 大约一半的地方有一个“使用SQL模型类”的标题,上面有一些很好的例子。在

我的回答是

def handlebutton(self):
    rows = self.tableView.selectionModel().selectedIndexes()
    print(self.projectModel.record(rows[0].row()).value("rowid"))
    self.newwindow = classformularesult(self)
    self.newwindow.show()

谢谢你SEGFAULTCODER

相关问题 更多 >