raton
raton

Reputation: 428

Adding a combobox in my tablewidget

I want to add a combobox in my tablewidget cell. When I will click on the cell the combobox will appear.

It is appearing but the problem is when I click the cells one after another it shows combobox is deleted?

import sys
from PyQt4 import QtGui, QtCore


class mainwin(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.resize(500, 700)


        self.comb = QtGui.QComboBox()
        self.comb.addItem("raton")


        self.table =QtGui.QTableWidget(self)
        self.table.setColumnCount(3)
        self.table.setRowCount(4)

        self.table.cellClicked.connect(self.addcomb)

   def addcomb(self,row,col):
        self.table.setCellWidget(row, col, self.comb)

What is the problem?

Upvotes: 3

Views: 3327

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

A widget can't be placed in two places at a time. When you put it into the 2nd cell, it disappears from the 1st because of that. But the 1st cell doesn't know about it and still keeps ownership of the widget. When you click the 1st cell again and call setCellWidget, it deletes its previous object as noted in the documentation. So your combobox is now lost for good.

There is no way to take ownership of the combobox once you've placed it into the table. So I think you need to create new combobox each time you want to set a cell widget.

If you still want to keep a single combobox in the table, you can delete previous combobox before creating new:

    self.old_row = -1
    self.old_col = -1

  def addcomb(self,row,col):
    if self.old_row >= 0:
      self.table.setCellWidget(self.old_row, self.old_col, None)
    self.old_row = row
    self.old_col = col
    comb = QtGui.QComboBox()
    comb.addItem("raton")
    self.table.setCellWidget(row, col, comb)

Upvotes: 4

Related Questions