How to change background color of a cell in a treeview at runtime please?



  • What I use is QSqlQueryModel + QTreeView.
    I am planning to change background color of a cell in a treeview by double clicking the cell, the following are the codes, but it won't work.
    Please tell me what is wrong with them . Thanks a lot.

    @
    void MainWindow::on_tableViewMain_doubleClicked(QModelIndex index)
    {
    processTableViewMainDoubleClicked(index);
    ui->tableViewMain->model->setData(index,QVariant(QColor(Qt::red)),Qt::BackgroundRole);
    ui->tableViewMain->update(index);
    }
    @

    EDIT: inserted @-tags for code, Gerolf. Please use that in future for code formatting



  • I don't know whether a QSqlQueryModel allows storing of such data.
    You could achieve it by using a proxy model.



  • Problem solved by Implementing a Custom Delegate Inherits QStyledItemDelegate.



  • Can you show the solution?

    [quote author="hpgh" date="1296664055"]Problem solved by Implementing a Custom Delegate Inherits QStyledItemDelegate.
    [/quote]



  • What I want to do is that the whole row will change the background color when I double click a cell in the row.
    So I wrote my own paint method in MyItemDelegate class inherits QStyledItemDelegate:

    @
    void MyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
    int row = index.row();
    if(row == myrow)
    {
    painter->fillRect(option.rect, mycolor);
    QStyledItemDelegate::paint(painter,option,index);
    }
    else
    {
    QStyledItemDelegate::paint(painter,option,index);
    }
    }

    and the following is response function of double-click event.

    void MainWindow::processTableViewMainDoubleClicked(QModelIndex &index)
    {
    ...
    ...
    // Mark the line when double clicked.
    ui->tableViewMain->setItemDelegate(new MyItemDelegate(row, QColor(Qt::yellow)));
    ...
    }

    @



  • hi hpgh, can you use the @ tag to make the code more readable. thanks



  • [quote author="chetankjain" date="1297153689"]hi hpgh, can you use the @ tag to make the code more readable. thanks[/quote]

    I will pay attention next time.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.