PDA

View Full Version : QTreeView and Column/Row Gridlines



smhall316
11th July 2013, 20:27
I have seen this question asked before, but I did not quite see an answer that cleared it up for me. A QTreeView has rows and columns. Is there a way to draw gridlines so that each row and column is clearly outlined or just vertical lines to separate columns? I looked at Qt Designer and their Property Editor does this. Does creating a feature like this require reimplementing the drawRow function or is there a straight forward way to do this?

Thanks in advance

Santosh Reddy
12th July 2013, 04:57
You could use a delegate


class GridDelegate : public QStyledItemDelegate
{
public:
explicit GridDelegate(QObject * parent = 0) : QStyledItemDelegate(parent) { }

void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
painter->save();
painter->setPen(QColor(Qt::black));
painter->drawRect(option.rect);
painter->restore();

QStyledItemDelegate::paint(painter, option, index);
}
};

int main(int argc, char ** argv)
{
QApplication app(argc, argv);

QStandardItemModel model;
model.setRowCount(5);
model.setColumnCount(5);

for(int r = 0; r < model.rowCount(); r++)
for(int c = 0; c < model.columnCount(); c++)
model.setItem(r, c, new QStandardItem("Item"));

QTreeView treeView;
treeView.setModel(&model);
treeView.setItemDelegate(new GridDelegate(&treeView));
treeView.show();

return app.exec();
}