How do I assign a border to a specific QTableWidgetItem or a row in a QTableWidget?
Asked Answered
E

2

4

I am trying to make certain cells in my QTableWidget have different colored borders based on the information contained in an item(cell).

I do not want to select those cells and use the selection-color styles because different cells need to be selected/highlighted.

for ex. I have a table with 3 columns and 3 rows. All the cells have simple text in each of them.
[] [Name] [Value] [Units]
[1] [one] [1] [cm]
[2] [two] [2] [in]
[3] [three][3] [m]

The 1st row is selected by the user and is highlighted, a process in the background updates the values in the table and updates the value in the 3rd row to 4. Now I want to make the 3rd row have a red border around it.

Elwandaelwee answered 31/8, 2011 at 19:25 Comment(0)
Y
8

To change the border itself you'll probably need to create a custom delegate that does something along these lines:

class MyDelegate : public QItemDelegate {
  public:
    MyDelegate( QObject *parent ) : QItemDelegate( parent ) { }
    void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const {
      QItemDelegate::paint( painter, option, index );
      if( /* some condition */ ) {
         painter->setPen( Qt::red );
         painter->drawRect( option.rect );
      }
    }
}

Then you can call:

myTableWidget->setItemDelegate( new MyDelegate(this) );

You can use QTableWidgetItem::setData() and the QModelIndex::data() functions to pass the necessary information back and forth between your table and the delegate

See the qt documentation for QItemDelegate

Yan answered 31/8, 2011 at 22:31 Comment(4)
Thank you very much. This is exactly what I was looking for. I do have a question about the if( some condition ) part and how exactly to set that information for each cell. Can you help me with that? I edited my question above to include the code that I need help with. Thanks.Elwandaelwee
As stated in my answer, use QTableWidgetItem::setData() to get the information you need stored in the model. It can then be retrieved in your delegate by calling data() on your QModelIndex object.Yan
From the docs: "QAbstractItemView does not take ownership of delegate." and therefore you can't just create a new object inside of the method call w/o setting it's parent properly.Feebleminded
@chris can you please tell me in pyqt4. I have same issue in my program, i need to remove border of the particular row but i tried many ways those are not working perfectly.if you knew can you please tell meFlofloat
E
0

AFAIK, you can highlight the cell with a different color. I don't see any option that changes only the border of the cell.

Euchre answered 31/8, 2011 at 19:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.