0

I have a database and I want to add a button into a cell, like this:

example

After pressing the button I want to open a filedialog to get the path of selected file. The path should be saved and visible in the cell . But I couldnt achieve it to add the button. Is this possible with QTableView? I tried some code that I found here on stackoverflow, but the solution I found was only for QTableWidget and QStandardItemModel. I need it for QTableView. If I change QTableView to QTableWidget I cant set the model to QSqlDatabase:

TypeError: QTableWidget.setModel() is a private method

This is my code:

def setupUi(self, MainWindow):
    self.viewer = QTableView()
    self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    self.model = QtSql.QSqlTableModel()
    self.viewer.verticalHeader().setVisible(False)
    self.viewer.setModel(self.model)
    self.layout = QGridLayout()
    self.layout.addWidget(self.viewer, 0, 0, 1, 4)


def __init__(self):
    super().__init__()
    self.setupUi(self)
    self.show()

    tablelist = []
    with open('tmp2.tmp', 'r') as file:
        fileName = file.read()
    if fileName:
        self.db.close()
        self.dbfile = fileName
        self.conn = sqlite3.connect(self.dbfile)
        cur = self.conn.cursor()
        res = self.conn.execute("SELECT name FROM sqlite_master WHERE         type='table';")
        for name in res:
            print(name[0])
            tablelist.append(name[0])
        self.db.setDatabaseName(self.dbfile)
        self.db.open()
        self.tablename = "Database"
        print("DB is:", self.dbfile)
        self.initializeModel()

def initializeModel(self):
    print("Table selected:", self.tablename)
    self.model.setTable(self.tablename)
    self.model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
    self.model.select()
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • You say "I tried some code that I found here on stackoverflow, but it didnt work.", but in your code there's no trace of it, it just creates a table and connects to a database, which has nothing to do with what you're asking. If you did try something, then you should show us *that* attempt, even if it's not working, and you should leave out anything else that is unnecessary to the question. – musicamante Jan 21 '22 at 12:06
  • Sorry, my mistake. I will edit my post now. Thanks! – sta_rtsrfce Jan 21 '22 at 18:57
  • The solution in the second link does exactly what you need, just read the documentation of [`setIndexWidget()`](https://doc.qt.io/qt-5/qabstractitemview.html#setIndexWidget). `self.viewer.setIndexWidget(self.model.index(row, column), QPushButton("button"))`. – musicamante Jan 21 '22 at 19:21
  • Thanks a lot, I marked this as solution. – sta_rtsrfce Jan 22 '22 at 21:39

0 Answers0