PDA

View Full Version : QTreeView editor always visible



Alundra
13th March 2014, 00:47
Hi all,
Based on this post :
http://www.qtcentre.org/threads/24094-how-to-make-the-editor-wiget-always-visible-in-QTableView
There is a new way of achieve that using traditional delegate ?
Thanks for the help

ChrisW67
13th March 2014, 04:45
You can use real widgets applied to the cells as in the thread you linked to. This is OK for small fixed numbers of rows but does not scale well.

You can achieve a similar effect using a delegate by using the paint() function to draw a static image of the desired widget when the cell is not in edit mode. You could manually draw the equivalent of the widget, or use a real instance of the widget and QWidget::render() it. Here is a primitive example that fakes a spin box editor:


#include <QApplication>
#include <QTableWidget>
#include <QStyledItemDelegate>
#include <QScopedPointer>
#include <QSpinBox>
#include <QPainter>

class Delegate: public QStyledItemDelegate
{
Q_OBJECT
public:
Delegate(QObject *p = 0):
QStyledItemDelegate(p),
spin(new QSpinBox)
{
}

void paint (QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (!index.isValid()) return;

const int value = index.data(Qt::EditRole).toInt();
spin->setValue(value);
spin->setFrame(false);
spin->resize(option.rect.size());
QPixmap pixmap(option.rect.size());
QPainter p(&pixmap);
spin->render(&p);
p.end();

painter->drawPixmap(option.rect, pixmap);
}

private:
QScopedPointer<QSpinBox> spin;
};


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

QTableWidget t(10, 2);
t.setItemDelegateForColumn(1, new Delegate(&t));
for (int i = 0; i < 10; ++i) {
QTableWidgetItem *item = new QTableWidgetItem(QString("Row %1").arg(i));
t.setItem(i, 0, item);
item = new QTableWidgetItem;
item->setData(Qt::EditRole, i);
t.setItem(i, 1, item);
}
t.show();

return app.exec();
}
#include "main.moc"

For production use with a complex editor widget you might cache pixmaps.