Home > Enterprise >  If column doesn't exist, create it and setText - if it does exist, check for text and use next
If column doesn't exist, create it and setText - if it does exist, check for text and use next

Time:12-21

Effectively I want to increment columns, the first column is 3, which won't exist initially. Generate the column, and fill it with text from a label. For follow-on, check if row, column 3 has text, and if it does - create a new column, if not, set the text from label

Here's what I have so far, currently it will increment the column generation appropriately, but when I go to the next item in the list it will continue incrementing. I want it to go back and check column 3 again for text

def gen_cols(self, row, col, header):
    item = self.table.item(row, col)
    if item is None:
        item = QTableWidgetItem()
        header_item = QtWidgets.QTableWidgetItem(header)
        self.table.insertColumn(col)
        self.table.setHorizontalHeaderItem(col, header_item)
        self.table.setItem(row, col, item)
    return item

def update_table(self, s):
    header = 'Image: '   str(self.count)
    row = self.table.currentItem().row()
    self.col = self.table.columnCount()

    # item = self.gen_cols(row, col, header)
    item = self.table.item(row, self.col)
    if not item:
        item = self.gen_cols(row, self.col, header)
        item.setText(s)
    self.count  = 1

Here is what it currently does

Here is desired behavior

CodePudding user response:

QTableWidget is a bit peculiar, because even if the model has a specified row and column count, item() might return None if no data has been set.

A QTableWidgetItem is returned only in these two cases:

  • an item has been programmatically created using setItem();
  • data has been entered by the user;

This means that, for what you need, it's not enough to check if item() doesn't return None, you have to check if the index is actually valid before creating a new column. In your case, we can assume that an index is valid if its column is less than the column count.

def update_table(self, s):
    row = self.table.currentItem().row()
    maxColumn = self.table.columnCount()
    col = 2
    while col < maxColumn:
        item = self.table.item(row, col)
        if item is None:
            item = QTableWidgetItem()
            self.table.setItem(row, col, item)
        if not item.text():
            break
        col  = 1
    else:
        header = 'Image: '   str(self.count)
        item = self.gen_cols(row, col, header)
    
    item.setText(s)
    self.count  = 1
  • Related