Russian Qt Forum
Октябрь 03, 2024, 18:24 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1]   Вниз
  Печать  
Автор Тема: Ещё один очень тупой вопрос по Model/View  (Прочитано 3998 раз)
troorl
Гость
« : Июль 05, 2007, 17:05 »

Это снова я со своим вопросом =)
Имеем QListView, имеем наследника от QAbstractListModel. Делал тестовую заготовку - всё работает, мой QStringList отображается.

Мне захотелось, чтобы элементы списка отображались так, как мне надо. Сделал свой виджет, который принимает и отображает QString. Сам по себе он работает. Сделал наследника от QItemDelegate, засунул туда свой виджет. По идее всё должно работать. Но не работает. После установки моего делегата в QListView ничего не отображается Грустный

Вопрос. Что и как нужно определить в моём случае, чтобы в QListView отображались элементы списка в моих виджетах? Спасибо.
Записан
Racheengel
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2679


Я работал с дискетам 5.25 :(


Просмотр профиля
« Ответ #1 : Июль 05, 2007, 22:33 »

а код делегата можно нарисовать?
Записан

What is the 11 in the C++11? It’s the number of feet they glued to C++ trying to obtain a better octopus.

COVID не волк, в лес не уйдёт
troorl
Гость
« Ответ #2 : Июль 05, 2007, 23:44 »

Цитата: "Racheengel"
а код делегата можно нарисовать?

Можно конечно, но он самый стандартный, слизаный их ассистанта.
Код:
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);
}
Записан
vaprele07
Гость
« Ответ #3 : Июль 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();
}
Записан
troorl
Гость
« Ответ #4 : Июль 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();
}
Записан
vaprele07
Гость
« Ответ #5 : Июль 06, 2007, 13:18 »

переопределял sizeHint?
Записан
troorl
Гость
« Ответ #6 : Июль 06, 2007, 20:43 »

Цитата: "vaprele07"
переопределял sizeHint?

Да, взял наугад произвольный размер - return QSize(50, 30);
Совсем что-то запутался, не хочет оно рисоваться  :oops:

добавлено спустя 6 часов 23 минуты:

 Блин, у меня уже мозги плавятся. Может кто-нибудь дать рабочий пример реализации особого вида QItemDelegate? Зарание благодарю.
Записан
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.062 секунд. Запросов: 23.