Setting the value of one cell in QTableWidget fills everything.

Discussion in 'Python' started by Constantly Distracted, Mar 28, 2008.

  1. I've just started PyQt programming and I've run into this little
    problem. When I set the text of one cell in my table, all the other
    cells fill with that value.

    All I wanted to do was run a loop, printing in each cell the row and
    column number.
    Here's the code.

    ------------------------------

    from PyQt4 import QtGui,QtCore
    import sys

    class mywindow(QtGui.QWidget):
    def __init__(self,parent=None):
    QtGui.QWidget.__init__(self,parent)
    self.resize(700,700)
    self.mytable=QtGui.QTableWidget(7,6,self)
    self.mytable.resize(700,700)

    def filltable(self):
    items=QtGui.QTableWidgetItem()
    for column in range(self.mytable.columnCount()):
    for row in range(self.mytable.rowCount()):
    items.setText("row: " + str(row) + " column: " +
    str(column))
    self.mytable.setItem(row,column,items)


    app=QtGui.QApplication(sys.argv)
    mainwin=mywindow()
    mainwin.filltable()
    qb.show()
    app.exec_()
     
    Constantly Distracted, Mar 28, 2008
    #1
    1. Advertisements

  2. En Fri, 28 Mar 2008 12:01:01 -0300, Constantly Distracted
    Here you create a *single* object named item [why not "item" instead?]
    Here you set the *same* item all over the table.
     
    Gabriel Genellina, Mar 28, 2008
    #2
    1. Advertisements

  3. ....because you have only created a single QTableWidgetItem instance, rather
    than one for each cell.
    Move the creation of the QTableWidgetItem() to the inner loop (and call
    it "item" rather than "items").

    Phil
     
    Phil Thompson, Mar 28, 2008
    #3
  4. Move the creation of the QTableWidgetItem() to the inner loop (and call
    Thanks, that works perfectly.
     
    Constantly Distracted, Mar 29, 2008
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.