Python Forum
How to update the list of a combo box in a QTableView
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to update the list of a combo box in a QTableView
#1
Panoss about 2 hours ago

I have a problem refreshing the data in the list of a combo box in a QTableView.
When you run the program (I have put all the classes in one file for your convenience) it wil create a database and will display a form titled "Articles".
It displays data of the db table 'articles'.
The field with the title 'positions' is related to table 'positions'.

-click button 'Edit positions' and the form with the title 'Positions - edit' will be displayed.
-click button 'Add new position'and a form with the title 'Add new position' will show up.
-enter the name of the new position (e.g. 'Drawer 4') and click ok
-now you see the previous form (with the title 'Positions - edit')
-the new position you entered appears in the list
-click 'Refresh Articles' (refreshes the model ('ArticlesModel') of the first form (the form with the title "Articles"))
-close this form
-now you see the first form (with the title "Articles")
-click on any cell on the field 'positions' and look at the list of the combo box
-you won't see the new position you entered before!

So, this is my problem, that the field with the title 'positions' in the TableView does not update.
If you look in the code you will see that I update TableView 's model (with a Signal - slot mechanism).
How can I update this list of the combo box?
(If you close and rerun the program you see just fine the new position in the list of the combo)
#
# Created by: PyQt6 UI code generator 6.2.3
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt6 import QtCore, QtWidgets
from PyQt6.QtCore import Qt, QObject
from PyQt6.QtWidgets import QMainWindow, QPushButton, QDialog, QVBoxLayout
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QApplication
from PyQt6.QtSql import QSqlRelation, QSqlRelationalTableModel, QSqlTableModel, QSqlRelationalDelegate



class myWindow(QMainWindow):
    """A window to show the articles available"""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        #create and init db
        init_db()

        ######################################################
        #####################  V I E W  ######################
        ######################################################
        self.setWindowTitle("Articles")
        self.resize(550, 250)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.layout = QVBoxLayout()
        # add QTableView
        self.ArticlesTableView = QtWidgets.QTableView(self)
        self.ArticlesTableView.setObjectName("ArticlesTableView")
        self.layout.addWidget(self.ArticlesTableView)
        # add button
        self.button = QPushButton(self)
        self.button.setObjectName("button")
        self.button.setText("Edit positions")
        self.layout.addWidget(self.button)
        self.button.clicked.connect(self.button_clicked)
        # set central the self.layout
        self.centralWidget.setLayout(self.layout)
        ######################################################
        ####################  M O D E L  #####################
        ######################################################
        self.ArticlesModel = QSqlRelationalTableModel(self.ArticlesTableView)
        self.ArticlesModel.setEditStrategy(QSqlTableModel.EditStrategy.OnFieldChange)
        self.ArticlesModel.setTable("articles")
        self.ArticlesTableView.setModel(self.ArticlesModel)
        position_idx = self.ArticlesModel.fieldIndex("position")
        self.ArticlesModel.setRelation(position_idx, QSqlRelation("positions", "id", "name"))
        if not self.ArticlesModel.select():
            print(self.ArticlesModel.lastError())

        self.ArticlesTableView.setItemDelegate(QSqlRelationalDelegate(self.ArticlesTableView))
        self.ArticlesModel.setHeaderData(position_idx, QtCore.Qt.Orientation.Horizontal, "position")

    def button_clicked(self):
        # open form Positions which displays the positions
        myDialog = Positions()
        # Should recieve signal (signalRefreshArticlesModel) from Position form
        myDialog.signalRefreshArticlesModel.connect(self.RefreshArticlesModel)
        myDialog.exec()

    @QtCore.pyqtSlot()
    def RefreshArticlesModel(self):
        print("Articles Form: Refresh Articles Model called!")
        if not self.ArticlesModel.select():
            print("Articles Form: " + self.ArticlesModel.lastError())
##########################################################
class Ui_dialog_add_new(object):
    def setupUi(self, dialog_in):
        dialog_in.setObjectName("dialog_in")
        dialog_in.resize(400, 146)
        self.setWindowTitle("Add new position")

        self.setModal(True)
        print("fieldName 0=" + self.model.record().fieldName(0) + " fieldName 1=" + self.model.record().fieldName(1))
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(dialog_in)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.positionLabel = QtWidgets.QLabel(dialog_in)
        self.positionLabel.setObjectName("positionLabel")
        self.horizontalLayout_2.addWidget(self.positionLabel)
        self.positionEdit = QtWidgets.QLineEdit(dialog_in)
        self.positionEdit.setObjectName("positionEdit")
        self.horizontalLayout_2.addWidget(self.positionEdit)
        self.horizontalLayout_2.setStretch(0, 1)
        self.horizontalLayout_2.setStretch(1, 4)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.authorLabel = QtWidgets.QLabel(dialog_in)
        self.authorLabel.setObjectName("authorLabel")
        self.horizontalLayout_3.addWidget(self.authorLabel)
        #self.authorNameCombo = QtWidgets.QComboBox(dialog_in)
        #self.authorNameCombo.setObjectName("authorNameCombo")
        #self.horizontalLayout_3.addWidget(self.authorNameCombo)
        self.horizontalLayout_3.setStretch(0, 1)
        self.horizontalLayout_3.setStretch(1, 4)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum,
                                           QtWidgets.QSizePolicy.Policy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding,
                                            QtWidgets.QSizePolicy.Policy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.okButton = QtWidgets.QPushButton(dialog_in)

        self.okButton.setObjectName("okButton")
        self.okButton.setText("Ok")

        self.okButton.clicked.connect(self.okButton_clicked)
        self.horizontalLayout.addWidget(self.okButton)
        self.cancelButton = QtWidgets.QPushButton(dialog_in)
        self.cancelButton.setObjectName("cancelButton")
        self.cancelButton.setText("Cancel")
        self.cancelButton.clicked.connect(self.cancelButton_clicked)
        self.horizontalLayout.addWidget(self.cancelButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_3.addLayout(self.verticalLayout_2)
        QtCore.QMetaObject.connectSlotsByName(dialog_in)
    def cancelButton_clicked(self):
        print("cancelButton_clicked")
    def okButton_clicked(self):
        print("okButton_clicked")
        position=self.positionEdit.text()

        newRecord = self.model.record()
        newRecord.setValue("name", self.positionEdit.text())
        if (self.model.insertRecord(self.model.rowCount(), newRecord)) :
            print("New record inserted")
        else:
            print("FAILED to insert new record")

        self.model.submitAll()
        self.model.select()

        print("position=" + position)
        self.close()

class Dialog_add_new(QDialog, Ui_dialog_add_new):
    def __init__(self, parent=None, model=None):
        QDialog.__init__(self, parent)
        self.model = model
        self.setupUi(self)
##########################################################



class positions_dialog(object):
    signalRefreshArticlesModel = QtCore.pyqtSignal()
    def setupUi(self, positions_dialog_in):
        self.setObjectName("positions_dialog_in")
        self.resize(500, 300)
        self.setWindowTitle("Positions - edit")
        self.setModal(True)
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setObjectName("layout")

        self.tableView = QtWidgets.QTableView(self)
        self.tableView.setObjectName("tableView")
        self.layout.addWidget(self.tableView)

        self.AddNewButton = QtWidgets.QPushButton(self)
        self.AddNewButton.setObjectName("AddNewButton")
        self.AddNewButton.setText("Add new position")
        self.layout.addWidget(self.AddNewButton)
        self.AddNewButton.clicked.connect(self.add_new_button_clicked)

        self.RefreshArticlesButton = QtWidgets.QPushButton(self)
        self.RefreshArticlesButton.setObjectName("RefreshArticlesButton")
        self.RefreshArticlesButton.setText("Refresh Articles")
        self.layout.addWidget(self.RefreshArticlesButton)
        self.RefreshArticlesButton.clicked.connect(self.refresh_articles_button_clicked)


        model = QSqlRelationalTableModel(self.tableView)
        model.setEditStrategy(QSqlTableModel.EditStrategy.OnFieldChange)
        model.setTable("positions")
        self.model = model
        self.tableView.setModel(model)
        if not model.select():
            print(model.lastError())


    def add_new_button_clicked(self):
        myDialog = Dialog_add_new(self, self.model)
        #myDialog = Positions()
        myDialog.exec()
    def refresh_articles_button_clicked(self):
        print("refresh_articles_button_clicked")
        self.signalRefreshArticlesModel.emit()

class Positions(QDialog, positions_dialog):
    def __init__(self,parent=None):
        QDialog.__init__(self,parent)
        self.setupUi(self)
########################################################################################
########################################################################################



from PyQt6.QtSql import QSqlDatabase, QSqlQuery
from os.path import exists

def add_article(q, name, position):
    q.addBindValue(name)
    q.addBindValue(position)
    q.exec()

def add_posistion(q, name):
    q.addBindValue(name)
    #q.addBindValue(str(position))
    q.exec()
    return q.lastInsertId()

ARTICLES_SQL = """
    create table IF NOT EXISTS articles(id integer primary key, name varchar, position integer)
    """
POSITIONS_SQL = """
    create table IF NOT EXISTS positions(id integer primary key, name varchar)
    """
INSERT_ARTICLE_SQL = """
    insert into articles(name, position)
                values(?, ?)
    """
INSERT_POSITION_SQL = """
    insert into positions(name) values(?)
    """

def init_db():
    """
    init_db()
    Initializes the database.
    If tables "books" and "authors" are already in the database, do nothing.
    Return value: None or raises ValueError
    The error value is the QtSql error instance.
    """
    def check(func, *args):
        if not func(*args):
            raise ValueError(func.__self__.lastError())


    # returns false if db is not created
    file_exists = exists("inventory.db")
    print("file_exists=" + str(file_exists))
    # add db driver
    db = QSqlDatabase.addDatabase("QSQLITE")
    # set db (or create it if not exists)
    db.setDatabaseName("inventory.db")
    # open db
    check(db.open)
    #add data only if db is just created (so file_exists returned 'false')
    if not file_exists:
        q = QSqlQuery()
        check(q.exec, ARTICLES_SQL)
        check(q.exec, POSITIONS_SQL)

        check(q.prepare, INSERT_POSITION_SQL)
        position1 = add_posistion(q, "Drawer 1")
        position2 = add_posistion(q, "Drawer 2")
        position3 = add_posistion(q, "Drawer 3")


        check(q.prepare,INSERT_ARTICLE_SQL)
        add_article(q, "Gendora key 15", position1)
        add_article(q, "Foundation and Empire", position1)
        add_article(q, "Second Foundation", position2)
        add_article(q, "Foundation's Edge", position1)
        add_article(q, "Foundation and Earth", position2)
        add_article(q, "Prelude to Foundation", position3)
        add_article(q, "Forward the Foundation", position3)
        add_article(q, "The Power and the Glory", position3)
        add_article(q, "The Third Man", position1)
        add_article(q, "Our Man in Havana", position3)
        add_article(q, "Guards! Guards!", position1)
        add_article(q, "Night Watch", position2)
        add_article(q, "Going Postal", position1)

########################################################################################
#######################################################################################


if __name__ == "__main__":
    app = QApplication([])
    import sys
    window = myWindow()
    window.resize(800, 600)
    window.show()
    sys.exit(app.exec())
Reply
#2
At first glance this is noticeable.

        model = QSqlTableModel(self.tableView)
        model = QSqlRelationalTableModel(self.tableView)
The second eliminates the first.
panoss likes this post
Reply
#3
I removed the 'model = QSqlTableModel(self.tableView)'.
Reply
#4
The function UpdateArticlesModel only has print. Where is the database updated?
Reply
#5
(Feb-04-2022, 07:48 PM)Axel_Erfurt Wrote: The function UpdateArticlesModel only has print. Where is the database updated?

The 'articles' table does not get updated.
Only the 'positions' table gets updated (line 146).
(the list of the combo is populated by the data of the 'positions' table)

The articles model gets refreshed at line 67 (ok, I should have named it 'RefreshArticlesModel' instead of 'UpdateArticlesModel'):
@QtCore.pyqtSlot()
    def UpdateArticlesModel(self):
        print("Articles Form: Update Articles Model called!")
        if not self.ArticlesModel.select():
            print("Articles Form: " + self.ArticlesModel.lastError())
Reply
#6
I renamed it from 'UpdateArticlesModel' to 'RefreshArticlesModel' and updated the code in the first post.
Reply
#7
Ok, I found it!
I subclassed the QSqlRelationalDelegate:

# Created by: PyQt6 UI code generator 6.2.3
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QRegExpValidator
from PyQt6 import QtCore, QtWidgets
from PyQt6.QtCore import Qt, QObject
from PyQt6.QtWidgets import QMainWindow, QPushButton, QDialog, QVBoxLayout, QLineEdit, QComboBox
from PyQt6.QtWidgets import QWidget
from PyQt6.QtWidgets import QApplication
from PyQt6.QtSql import QSqlRelation, QSqlRelationalTableModel, QSqlTableModel, QSqlRelationalDelegate

import copy
from PyQt6.QtSql import QSqlRelationalDelegate
from PyQt6.QtGui import QPixmap

class myWindow(QMainWindow):
    """A window to show the articles available"""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        #create and init db
        init_db()

        ######################################################
        #####################  V I E W  ######################
        ######################################################
        self.setWindowTitle("Articles")
        self.resize(550, 250)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.layout = QVBoxLayout()
        # add QTableView
        self.ArticlesTableView = QtWidgets.QTableView(self)
        self.ArticlesTableView.setObjectName("ArticlesTableView")
        self.layout.addWidget(self.ArticlesTableView)
        # add button
        self.button = QPushButton(self)
        self.button.setObjectName("button")
        self.button.setText("Edit positions")
        self.layout.addWidget(self.button)
        self.button.clicked.connect(self.button_clicked)
        # set central the self.layout
        self.centralWidget.setLayout(self.layout)
        ######################################################
        ####################  M O D E L  #####################
        ######################################################
        self.ArticlesModel = QSqlRelationalTableModel(self.ArticlesTableView)
        self.ArticlesModel.setEditStrategy(QSqlTableModel.EditStrategy.OnFieldChange)
        self.ArticlesModel.setTable("articles")
        self.ArticlesTableView.setModel(self.ArticlesModel)
        position_idx = self.ArticlesModel.fieldIndex("position")
        self.ArticlesModel.setRelation(position_idx, QSqlRelation("positions", "id", "name"))
        if not self.ArticlesModel.select():
            print(self.ArticlesModel.lastError())

        self.ArticlesTableView.setItemDelegate(myDelegate(self.ArticlesTableView))
        self.ArticlesModel.setHeaderData(position_idx, QtCore.Qt.Orientation.Horizontal, "position")

    def button_clicked(self):
        # open form Positions which displays the positions
        myDialog = Positions()
        # Should recieve signal (signalRefreshArticlesModel) from Position form
        myDialog.signalRefreshArticlesModel.connect(self.RefreshArticlesModel)
        myDialog.exec()

    @QtCore.pyqtSlot()
    def RefreshArticlesModel(self):
        print("Articles Form: Refresh Articles Model called!")
        if not self.ArticlesModel.select():
            print("Articles Form: " + self.ArticlesModel.lastError())
##########################################################
class Ui_dialog_add_new(object):
    def setupUi(self, dialog_in):
        dialog_in.setObjectName("dialog_in")
        dialog_in.resize(400, 146)
        self.setWindowTitle("Add new position")

        self.setModal(True)
        print("fieldName 0=" + self.model.record().fieldName(0) + " fieldName 1=" + self.model.record().fieldName(1))
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(dialog_in)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.positionLabel = QtWidgets.QLabel(dialog_in)
        self.positionLabel.setObjectName("positionLabel")
        self.horizontalLayout_2.addWidget(self.positionLabel)
        self.positionEdit = QtWidgets.QLineEdit(dialog_in)
        self.positionEdit.setObjectName("positionEdit")
        self.horizontalLayout_2.addWidget(self.positionEdit)
        self.horizontalLayout_2.setStretch(0, 1)
        self.horizontalLayout_2.setStretch(1, 4)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.authorLabel = QtWidgets.QLabel(dialog_in)
        self.authorLabel.setObjectName("authorLabel")
        self.horizontalLayout_3.addWidget(self.authorLabel)
        #self.authorNameCombo = QtWidgets.QComboBox(dialog_in)
        #self.authorNameCombo.setObjectName("authorNameCombo")
        #self.horizontalLayout_3.addWidget(self.authorNameCombo)
        self.horizontalLayout_3.setStretch(0, 1)
        self.horizontalLayout_3.setStretch(1, 4)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Policy.Minimum,
                                           QtWidgets.QSizePolicy.Policy.Expanding)
        self.verticalLayout.addItem(spacerItem)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Policy.Expanding,
                                            QtWidgets.QSizePolicy.Policy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.okButton = QtWidgets.QPushButton(dialog_in)

        self.okButton.setObjectName("okButton")
        self.okButton.setText("Ok")

        self.okButton.clicked.connect(self.okButton_clicked)
        self.horizontalLayout.addWidget(self.okButton)
        self.cancelButton = QtWidgets.QPushButton(dialog_in)
        self.cancelButton.setObjectName("cancelButton")
        self.cancelButton.setText("Cancel")
        self.cancelButton.clicked.connect(self.cancelButton_clicked)
        self.horizontalLayout.addWidget(self.cancelButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_3.addLayout(self.verticalLayout_2)
        QtCore.QMetaObject.connectSlotsByName(dialog_in)
    def cancelButton_clicked(self):
        print("cancelButton_clicked")
    def okButton_clicked(self):
        print("okButton_clicked")
        position=self.positionEdit.text()

        newRecord = self.model.record()
        newRecord.setValue("name", self.positionEdit.text())
        if (self.model.insertRecord(self.model.rowCount(), newRecord)) :
            print("New record inserted")
        else:
            print("FAILED to insert new record")

        self.model.submitAll()
        self.model.select()

        print("position=" + position)
        self.close()

class Dialog_add_new(QDialog, Ui_dialog_add_new):
    def __init__(self, parent=None, model=None):
        QDialog.__init__(self, parent)
        self.model = model
        self.setupUi(self)
##########################################################



class positions_dialog(object):
    signalRefreshArticlesModel = QtCore.pyqtSignal()
    def setupUi(self, positions_dialog_in):
        self.setObjectName("positions_dialog_in")
        self.resize(500, 300)
        self.setWindowTitle("Positions - edit")
        self.setModal(True)
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setObjectName("layout")

        self.tableView = QtWidgets.QTableView(self)
        self.tableView.setObjectName("tableView")
        self.layout.addWidget(self.tableView)

        self.AddNewButton = QtWidgets.QPushButton(self)
        self.AddNewButton.setObjectName("AddNewButton")
        self.AddNewButton.setText("Add new position")
        self.layout.addWidget(self.AddNewButton)
        self.AddNewButton.clicked.connect(self.add_new_button_clicked)

        self.RefreshArticlesButton = QtWidgets.QPushButton(self)
        self.RefreshArticlesButton.setObjectName("RefreshArticlesButton")
        self.RefreshArticlesButton.setText("Refresh Articles")
        self.layout.addWidget(self.RefreshArticlesButton)
        self.RefreshArticlesButton.clicked.connect(self.refresh_articles_button_clicked)


        model = QSqlRelationalTableModel(self.tableView)
        model.setEditStrategy(QSqlTableModel.EditStrategy.OnFieldChange)
        model.setTable("positions")
        self.model = model
        self.tableView.setModel(model)
        if not model.select():
            print(model.lastError())


    def add_new_button_clicked(self):
        myDialog = Dialog_add_new(self, self.model)
        #myDialog = Positions()
        myDialog.exec()
    def refresh_articles_button_clicked(self):
        print("refresh_articles_button_clicked")
        self.signalRefreshArticlesModel.emit()

class Positions(QDialog, positions_dialog):
    def __init__(self,parent=None):
        QDialog.__init__(self,parent)
        self.setupUi(self)
########################################################################################
########################################################################################



from PyQt6.QtSql import QSqlDatabase, QSqlQuery
from os.path import exists

def add_article(q, name, position):
    q.addBindValue(name)
    q.addBindValue(position)
    q.exec()

def add_posistion(q, name):
    q.addBindValue(name)
    #q.addBindValue(str(position))
    q.exec()
    return q.lastInsertId()

ARTICLES_SQL = """
    create table IF NOT EXISTS articles(id integer primary key, name varchar, position integer)
    """
POSITIONS_SQL = """
    create table IF NOT EXISTS positions(id integer primary key, name varchar)
    """
INSERT_ARTICLE_SQL = """
    insert into articles(name, position)
                values(?, ?)
    """
INSERT_POSITION_SQL = """
    insert into positions(name) values(?)
    """

def init_db():
    """
    init_db()
    Initializes the database.
    If tables "books" and "authors" are already in the database, do nothing.
    Return value: None or raises ValueError
    The error value is the QtSql error instance.
    """
    def check(func, *args):
        if not func(*args):
            raise ValueError(func.__self__.lastError())


    # returns false if db is not created
    file_exists = exists("inventory.db")
    print("file_exists=" + str(file_exists))
    # add db driver
    db = QSqlDatabase.addDatabase("QSQLITE")
    # set db (or create it if not exists)
    db.setDatabaseName("inventory.db")
    # open db
    check(db.open)
    #add data only if db is just created (so file_exists returned 'false')
    if not file_exists:
        q = QSqlQuery()
        check(q.exec, ARTICLES_SQL)
        check(q.exec, POSITIONS_SQL)

        check(q.prepare, INSERT_POSITION_SQL)
        position1 = add_posistion(q, "Drawer 1")
        position2 = add_posistion(q, "Drawer 2")
        position3 = add_posistion(q, "Drawer 3")


        check(q.prepare,INSERT_ARTICLE_SQL)
        add_article(q, "Gendora key 15", position1)
        add_article(q, "Foundation and Empire", position1)
        add_article(q, "Second Foundation", position2)
        add_article(q, "Foundation's Edge", position1)
        add_article(q, "Foundation and Earth", position2)
        add_article(q, "Prelude to Foundation", position3)
        add_article(q, "Forward the Foundation", position3)
        add_article(q, "The Power and the Glory", position3)
        add_article(q, "The Third Man", position1)
        add_article(q, "Our Man in Havana", position3)
        add_article(q, "Guards! Guards!", position1)
        add_article(q, "Night Watch", position2)
        add_article(q, "Going Postal", position1)

########################################################################################
#######################################################################################
class myDelegate(QSqlRelationalDelegate):
    """Books delegate to rate the books"""

    def __init__(self, parent=None):
        print("myDelegate __init__")
        QSqlRelationalDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        # column of combo box 'position'
        positionColumn = 2
        print("myDelegate.createEditor index.column()=" + str(index.column()) + " option=" + str(option) )
        if index.column() == positionColumn:
            editor = QSqlRelationalDelegate.createEditor(self, parent, option, index)
            if isinstance(editor, QComboBox):
                editor.model().select()
            return editor
        else:
            return super(myDelegate, self).createEditor(parent, option, index)
##################################################################################

if __name__ == "__main__":
    app = QApplication([])
    import sys
    window = myWindow()
    window.resize(800, 600)
    window.show()
    sys.exit(app.exec())
Reply
#8
But it cannot be changed.
After changing in the ComboBox it jumps back to the original value when clicking on another row.

Output:
myDelegate.createEditor index.column()=2 option=<PyQt6.QtWidgets.QStyleOptionViewItem object at 0x7f6f1fbb4f90>
Reply
#9
I don't understand what you 're saying, it works fine for me.
Reply
#10
Use Add new Position then try to change position to the new created does not work.

It works after restarting the script.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyQt] PyQt5 QTableView SQLite : edit cell HeinKurz 2 2,411 Mar-27-2023, 10:41 AM
Last Post: HeinKurz
Photo PySimpleGUI FilesBrowse enable event to update value in combo SamLiu 2 4,624 Mar-15-2023, 12:49 PM
Last Post: SamLiu
  [PyQt] QStyledItemDelegate and QTableView malonn 1 1,651 Feb-07-2023, 07:15 PM
Last Post: malonn
  [PyQt] QTableView set header labels HeinKurz 2 6,824 Jan-23-2023, 08:46 AM
Last Post: HeinKurz
  [PyQt] Determine whether text in QTableView cell is fully visible or not random_nick 0 991 Oct-27-2022, 09:29 PM
Last Post: random_nick
  [PyQt] QTableView: scroll to top cell of the screen random_nick 2 2,857 Oct-08-2022, 12:29 AM
Last Post: random_nick
  [PyQt] [Solved]Add a Blank Row To QTableView Extra 3 5,568 Oct-02-2022, 04:53 PM
Last Post: Extra
  Radio butto to enable/disable combo box in Tkinter cybertooth 5 5,548 Oct-09-2021, 07:30 AM
Last Post: cybertooth
  [PyQt] How to Copy-Paste a table from Office apps to QTableView? Vittorio 5 7,267 Aug-05-2021, 11:14 AM
Last Post: Axel_Erfurt
  [Tkinter] how to update label text from list Roshan 8 5,468 Apr-25-2020, 08:04 AM
Last Post: Roshan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020