Results 1 to 4 of 4

Thread: Change color of a row of a QSqlQueryModel (QTableView)?

  1. #1
    Join Date
    Feb 2017
    Posts
    19
    Thanks
    5
    Qt products
    Qt5

    Default Change color of a row of a QSqlQueryModel (QTableView)?

    I 'm trying to change the color of rows in a QTableView which has a QSqlQueryModel as it's model.

    Here is a compilable code sample in python:
    Qt Code:
    1. import sys
    2. from PyQt4 import QtGui, QtCore, QtSql
    3.  
    4. def main():
    5. app = QtGui.QApplication(sys.argv)
    6. w = MyWindow()
    7. w.show()
    8. sys.exit(app.exec_())
    9.  
    10. class MyWindow(QtGui.QTableView):
    11. def __init__(self, *args):
    12. QtGui.QTableView.__init__(self, *args)
    13.  
    14. # connect to db (if doesn't exist, it's auto-created)
    15. self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    16. self.db.setDatabaseName('test.db')
    17. self.db.open()
    18.  
    19. #create a table in db and add some data
    20. query = QtSql.QSqlQuery()
    21. query.exec_("DROP TABLE IF EXISTS games")
    22. query.exec_("CREATE TABLE games(id INTEGER PRIMARY KEY, hometeam TEXT, visitorteam TEXT) ")
    23. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('Star', 'Eagles')")
    24. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('Best team', 'Reds');")
    25.  
    26. # set the model
    27. model = QtSql.QSqlQueryModel(self)#QtGui.QStandardItemModel(0, 2)
    28. self.setModel(model)
    29. model.setQuery("SELECT * FROM games")
    30.  
    31. # paint first two rows
    32. for i in range(0, 2):
    33. model.setData(model.index(i, 0), QtGui.QBrush(QtCore.Qt.red), QtCore.Qt.BackgroundRole)
    34. model.setData(model.index(i, 1), QtGui.QBrush(QtCore.Qt.red), QtCore.Qt.BackgroundRole)
    35.  
    36.  
    37. if __name__ == "__main__":
    38. main()
    To copy to clipboard, switch view to plain text mode 

    What am I doing wrong?

  2. #2
    Join Date
    Feb 2017
    Posts
    19
    Thanks
    5
    Qt products
    Qt5

    Default Re: Change color of a row of a QSqlQueryModel (QTableView)?

    I subclassed it:
    Qt Code:
    1. class ColorfullSqlQueryModel(QtSql.QSqlQueryModel):
    2. def __init__(self, dbcursor=None):
    3. super(ColorfullSqlQueryModel, self).__init__()
    4.  
    5. def data(self, QModelIndex, role=None):
    6. v = QtSql.QSqlQueryModel.data(self, QModelIndex, role);
    7. if role == QtCore.Qt.BackgroundRole:
    8. return QtGui.QColor(QtCore.Qt.yellow)
    9. return (v);
    To copy to clipboard, switch view to plain text mode 
    It works!! Turns all rows to yellow!
    But how can I make it paint only the rows I want?
    How can I pass the color to function data?

  3. #3
    Join Date
    Jan 2008
    Location
    Alameda, CA, USA
    Posts
    5,230
    Thanks
    302
    Thanked 864 Times in 851 Posts
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Change color of a row of a QSqlQueryModel (QTableView)?

    But how can I make it paint only the rows I want?
    How can I pass the color to function data?
    You can't pass any additional parameters to the data() method. If you need to set the color on an item-by-item basis, then you need to look at the row and column of the QModelIndex argument. Unless you can decide based on the row and column alone, generally you will need to implement an extra data structure in your custom model where you can look up the color for the index.
    <=== The Great Pumpkin says ===>
    Please use CODE tags when posting source code so it is more readable. Click "Go Advanced" and then the "#" icon to insert the tags. Paste your code between them.

  4. #4
    Join Date
    Feb 2017
    Posts
    19
    Thanks
    5
    Qt products
    Qt5

    Default Re: Change color of a row of a QSqlQueryModel (QTableView)?

    Finally, I ended in a, relatively, good solution:
    Qt Code:
    1. from PyQt4 import QtGui, QtCore, QtSql
    2. #from PyQt4.QtCore import *
    3. from PyQt4.QtGui import *
    4. import sys
    5.  
    6. def main():
    7. app = QtGui.QApplication(sys.argv)
    8. w = MyWindow()
    9. w.show()
    10. sys.exit(app.exec_())
    11.  
    12. class MyWindow(QtGui.QTableView):
    13. def __init__(self, *args):
    14. QtGui.QTableView.__init__(self, *args)
    15.  
    16. # connect to db (if doesn't exist, it's auto-created)
    17. self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    18. self.db.setDatabaseName('test.db')
    19. self.db.open()
    20.  
    21. #create a table in db and add some data
    22. query = QtSql.QSqlQuery()
    23. query.exec_("DROP TABLE IF EXISTS games")
    24. query.exec_("CREATE TABLE games(id INTEGER PRIMARY KEY, hometeam TEXT, visitorteam TEXT) ")
    25. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('Star', 'Eagles')")
    26. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('Best team', 'Reds');")
    27. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('NonWinners', 'Loosers');")
    28. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('North', 'South');")
    29. query.exec("INSERT INTO games (hometeam, visitorteam) VALUES ('East', 'west');")
    30.  
    31. # set the model
    32. model = CustomSqlModel(self)#QtGui.QStandardItemModel(0, 2)
    33. self.setModel(model)
    34. model.setQuery("SELECT * FROM games")
    35.  
    36. # paint first two rows
    37. model.setRowsToBeColored([0,3])
    38. for i in range(0, 2):
    39. index = QtCore.QModelIndex(model.index(i, 0))
    40. model.setData(index, QtCore.Qt.red, QtCore.Qt.BackgroundRole)
    41.  
    42.  
    43. class CustomSqlModel(QtSql.QSqlQueryModel):
    44. def __init__(self, dbcursor=None):
    45. super(CustomSqlModel, self).__init__()
    46. def setRowsToBeColored(self, rows):
    47. self.rows = rows
    48.  
    49. def data(self, index, role):
    50. row = index.row()
    51. print("row=", row, " row in self.rows=", row in self.rows)
    52. if role == QtCore.Qt.BackgroundRole and row in self.rows:
    53. return QBrush(QtCore.Qt.red)
    54. return QtSql.QSqlQueryModel.data(self, index, role);
    55.  
    56.  
    57. if __name__ == "__main__":
    58. main()
    To copy to clipboard, switch view to plain text mode 


    Added after 14 minutes:


    I have this c++ code, I want to 'translate' it (to python of course):
    Qt Code:
    1. #include <QIdentityProxyModel>
    2. class ExtraRolesProxyModel : public QIdentityProxyModel
    3. {
    4. Q_OBJECT
    5. Q_DISABLE_COPY(ExtraRolesProxyModel)
    6. public:
    7. explicit ExtraRolesProxyModel(QObject* parent=Q_NULLPTR)
    8. :QIdentityProxyModel(parent)
    9. {}
    10. virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE{
    11. const qint64 hashKey = (static_cast<qint64>(index.row()) << 32) | static_cast<qint64>(index.column());
    12. auto tableIter = m_extraRoles.constFind(hashKey);
    13. if(tableIter==m_extraRoles.constEnd())
    14. return QIdentityProxyModel::data(index,role);
    15. auto roleIter = tableIter.value().constFind(role);
    16. if(roleIter==tableIter.value().constEnd())
    17. return QIdentityProxyModel::data(index,role);
    18. return roleIter.value();
    19. }
    20. virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) Q_DECL_OVERRIDE {
    21. if(!index.isValid())
    22. return false;
    23. Q_ASSERT(index.model()==this);
    24. const qint64 hashKey = (static_cast<qint64>(index.row()) << 32) | static_cast<qint64>(index.column());
    25. if(value.isValid()){
    26. m_extraRoles[hashKey][role] = value;
    27. emit dataChanged(index,index,QVector<int>(1,role));
    28. return true;
    29. }
    30. auto tableIter = m_extraRoles.find(hashKey);
    31. if(tableIter==m_extraRoles.end())
    32. return false;
    33. auto roleIter = tableIter.value().find(role);
    34. if(roleIter==tableIter.value().end())
    35. return false;
    36. tableIter.value().erase(roleIter);
    37. if(tableIter.value().isEmpty())
    38. m_extraRoles.erase(tableIter);
    39. emit dataChanged(index,index,QVector<int>(1,role));
    40. return true;
    41. }
    42.  
    43. private:
    44. QHash<qint64,QHash<qint32,QVariant> > m_extraRoles;
    45. };
    To copy to clipboard, switch view to plain text mode 

    How do I translate this line?
    Qt Code:
    1. const qint64 hashKey = (static_cast<qint64>(index.row()) << 32) | static_cast<qint64>(index.column());
    To copy to clipboard, switch view to plain text mode 

    Ok, I translated it to:
    Qt Code:
    1. hashKey = index.row() << 32 | index.column()
    To copy to clipboard, switch view to plain text mode 
    Seems ok.

    But how about this one?
    Qt Code:
    1. auto tableIter = m_extraRoles.constFind(hashKey);
    To copy to clipboard, switch view to plain text mode 
    Last edited by panoss; 30th May 2017 at 09:14.

Similar Threads

  1. Change SqlQueryModel QTableView's Row Color
    By toadybarker in forum Qt Programming
    Replies: 9
    Last Post: 17th September 2014, 18:03
  2. Replies: 7
    Last Post: 25th July 2013, 21:47
  3. Replies: 7
    Last Post: 21st May 2013, 22:17
  4. how to change text color in QTableView?
    By phillip_Qt in forum Qt Programming
    Replies: 2
    Last Post: 28th April 2008, 10:03
  5. QTableView change color of current Cell
    By raphaelf in forum Qt Programming
    Replies: 4
    Last Post: 4th March 2006, 11:22

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.