元组索引超出范围(PyQt + Mysqldb)

时间:2014-09-09 14:26:45

标签: python mysql qt pyqt4 mysql-python

我从PyQt4中提出了一个表格,我从上一个答案中得到了一个例子,但我得到了#34; Tuple索引超出范围"。 我的代码如下。

 cursor.execute("SELECT id_cliente as 'Codigo del cliente', nombre AS 'Nombre' FROM t_clientes")
        row = cursor.fetchall()
        if row  == None:
            QtGui.QMessageBox.warning(self, "Error", "No hay Datos .... " , QtGui.QMessageBox.Ok)
            return
        ver_tabla.setRowCount(len(row))
        ver_tabla.setColumnCount(3)
        ##rellenamos la tabla con los datos ...
        for i in range (len(row)):
            for j in range (3):
                item = QTableWidgetItem('%s' % (row[i][j + 1]))
                ver_tabla.setItem(i, j, item)
        layout_btn_clientes.addWidget(ver_tabla,3,0,5,3)
  

文件" /home/admino/Proyectos/TM/recursosh.py",第102行, init       item = QTableWidgetItem('%s'%(row [i] [j + 1]))IndexError:元组索引超出范围

感谢您的帮助,我正在记录这些问题,我想,它很容易解决,但我找不到合适的答案

1 个答案:

答案 0 :(得分:0)

当我看到你的SQL代码时,结果应该是2列x N行(N是记录数);

SELECT id_cliente as 'Codigo del cliente', nombre AS 'Nombre' FROM t_clientes

所以,记录的tuple应该看起来像这样(2列x N行);

record = (
    (u'Data column 1.1', u'Data column 1.2'),
    (u'Data column 2.1', u'Data column 2.2'),
    ...
    (u'Data column M.N', u'Data column M.N'),
)

然后显示记录中的所有数据,方便循环for;

for row in range (len(record)):
    for column in range(len(record[row])): # For proof concept. I know is overhead, your can replace with 2.
        print record[row][column]

所以你的问题,问题是Index Out of Range,如python错误中所述。要修复它,请在使用之前通过计算使用正确的索引引用(不直接编码);

cursor.execute("SELECT id_cliente as 'Codigo del cliente', nombre AS 'Nombre' FROM t_clientes")
listsRecord = cursor.fetchall()
if listsRecord:
    QtGui.QMessageBox.warning(self, "Error", "No hay Datos .... " , QtGui.QMessageBox.Ok)
    return

lengthRow    = len(listsRecord)
lengthColumn = len(listsRecord[0]) # column is 2 at all
yourQTableWidget.setRowCount(lengthRow)
yourQTableWidget.setColumnCount(lengthColumn)
for row in range (lengthRow):
    for column in range (lengthColumn):
        itemQTableWidgetItem = QtGui.QTableWidgetItem(str(listsRecord[row][column]))
        yourQTableWidget.setItem(row, column, itemQTableWidgetItem)

测试示例;

import sys
from PyQt4 import QtGui

myQApplication   = QtGui.QApplication(sys.argv)
yourQTableWidget = QtGui.QTableWidget()
listsRecord = (('BRA001', 'ARCELIA EUGENIA'), ('DTA001', 'ALEJANDRA'), ('EDM001', 'ESPACIOS DE DISENO Y MUEBLES'), ('EIE001', 'EDMUNDO')) # Simulate data
lengthRow    = len(listsRecord)
lengthColumn = len(listsRecord[0])
yourQTableWidget.setRowCount(len(listsRecord))
yourQTableWidget.setColumnCount(lengthColumn)
for i in range (lengthRow):
    for j in range (lengthColumn):
        item = QtGui.QTableWidgetItem(str(listsRecord[i][j]))
        yourQTableWidget.setItem(i, j, item)
yourQTableWidget.show()
sys.exit(myQApplication.exec_())

实验结果:Windows 7,Python 2.7 x86,PyQt4

enter image description here