Название: Ещё один очень тупой вопрос по Model/View
Отправлено: troorl от Июль 05, 2007, 17:05
Это снова я со своим вопросом =) Имеем QListView, имеем наследника от QAbstractListModel. Делал тестовую заготовку - всё работает, мой QStringList отображается.
Мне захотелось, чтобы элементы списка отображались так, как мне надо. Сделал свой виджет, который принимает и отображает QString. Сам по себе он работает. Сделал наследника от QItemDelegate, засунул туда свой виджет. По идее всё должно работать. Но не работает. После установки моего делегата в QListView ничего не отображается :(
Вопрос. Что и как нужно определить в моём случае, чтобы в QListView отображались элементы списка в моих виджетах? Спасибо.
Название: Ещё один очень тупой вопрос по Model/View
Отправлено: Racheengel от Июль 05, 2007, 22:33
а код делегата можно нарисовать?
Название: Ещё один очень тупой вопрос по Model/View
Отправлено: troorl от Июль 05, 2007, 23:44
а код делегата можно нарисовать? Можно конечно, но он самый стандартный, слизаный их ассистанта. class TBookWidgetDelegate : public QItemDelegate { Q_OBJECT
public: TBookWidgetDelegate(QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; }; TBookWidgetDelegate::TBookWidgetDelegate(QObject *parent) : QItemDelegate(parent) { }
QWidget *TBookWidgetDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &/* index */) const { TBookWidget *editor = new TBookWidget(parent); return editor; }
void TBookWidgetDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString value = index.model()->data(index, Qt::DisplayRole).toString();
TBookWidget *bookWidget = static_cast<TBookWidget*>(editor); bookWidget->setData(value); }
void TBookWidgetDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { TBookWidget *bookWidget = static_cast<TBookWidget*>(editor); QString value = bookWidget->data();
model->setData(index, value); }
void TBookWidgetDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); }
Название: Ещё один очень тупой вопрос по Model/View
Отправлено: vaprele07 от Июль 06, 2007, 01:53
оно у тебя появится когда ты начнёшь редактировать элемент, а прорисовывает все дело paint примерно так: void GameListItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); GameListModel *model = (GameListModel*)index.model(); bool del = model->proxy()->isDeleted(index.row()); if (option.state & QStyle::State_Selected){ painter->fillRect(option.rect, option.palette.highlight()); painter->setPen(option.palette.highlightedText().color()); painter->setBrush(option.palette.highlightedText()); } else { if (del){ painter->setBrush(option.palette.button()); painter->setPen(option.palette.buttonText().color()); } else { painter->setBrush(option.palette.base()); } painter->fillRect(option.rect, painter->brush()); } // if (del){ QFont f = painter->font(); f.setItalic(true); f.setStrikeOut(true); painter->setFont(f); } // QRect itemRect; int f_x = option.rect.width() - option.rect.right(); int f_y = option.rect.y(); int itemHeight = option.fontMetrics.lineSpacing() + 2; // switch (model->viewStyle()){ case ShowPlaceText:{ int viewportWidth = option.rect.width() ; itemRect = QRect(-f_x, f_y, viewportWidth, itemHeight); painter->drawText( itemRect, Qt::AlignVCenter, QString("%1.").arg(index.row() + 1) ); // int k = columnWidth[0] + columnWidth[1]; if (f_x < k){ itemRect = QRect(columnWidth[0] - f_x, f_y , k, itemHeight); painter->drawText( itemRect, Qt::AlignVCenter, index.data().toStringList()[0] ); } // if (f_x < k + columnWidth[3]){ itemRect = QRect(k - f_x, f_y , viewportWidth, itemHeight); QFont f = painter->font(); f.setBold(true); painter->setFont(f); painter->drawText( itemRect, Qt::AlignVCenter, index.data().toStringList()[1] ); } break; } case ShowMoves:{ itemRect = QRect(f_x, f_y, maxItemWidth, itemHeight); painter->drawText(itemRect, Qt::AlignVCenter, index.data(Qt::DisplayRole).toStringList()[0]); break; } } // painter->restore(); }
Название: Ещё один очень тупой вопрос по Model/View
Отправлено: troorl от Июль 06, 2007, 13:05
Спасибо, оказывается я совсем всё не так понимал. Но всё же не получается у меня отрисовать хоть что-нибудь... В QListView по-прежнему пусто после установки делегата. Что я не так делаю? void TBookWidgetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if(option.state & QStyle::State_Selected) painter->fillRect(option.rect, option.palette.highlight()); painter->save(); painter->drawText(option.rect, Qt::AlignLeft, "Some text"); painter->restore(); }
Название: Ещё один очень тупой вопрос по Model/View
Отправлено: vaprele07 от Июль 06, 2007, 13:18
переопределял sizeHint?
Название: Ещё один очень тупой вопрос по Model/View
Отправлено: troorl от Июль 06, 2007, 20:43
переопределял sizeHint? Да, взял наугад произвольный размер - return QSize(50, 30); Совсем что-то запутался, не хочет оно рисоваться :oops: добавлено спустя 6 часов 23 минуты: Блин, у меня уже мозги плавятся. Может кто-нибудь дать рабочий пример реализации особого вида QItemDelegate? Зарание благодарю.
|