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

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

Страниц: [1]   Вниз
  Печать  
Автор Тема: QT414:QSqlQueryModel и QTableView, в ячейку виджет  (Прочитано 6207 раз)
Deiv
Гость
« : Октябрь 04, 2006, 14:34 »

тема картинки в ячейке хорошо описана в демке books при помощи "делегатов"
а как зафигачить в ячейку виджет например checkbox

впринципе наверное можно пихать checkbox туда напрямую
но есть слухи что этот метод память жрякает немеренно
а делегат сюда крутить - не знаю  :oops:

В форуме подобной темы ненашел - В общем посоветуйте  :roll:
Записан
igorko
Гость
« Ответ #1 : Октябрь 04, 2006, 17:13 »

Я делал делегат (только вставлял не чекбоксы а комбобоксы/дейтедиты и текстедиты) и вроде работает.
Записан
Deiv
Гость
« Ответ #2 : Октябрь 04, 2006, 20:27 »

Цитата: "igorko"
Я делал делегат (только вставлял не чекбоксы а комбобоксы/дейтедиты и текстедиты) и вроде работает.


Код глянуть можно?

Со звездами из демо\books ясно
painter->drawPixmap(x,y,star) в методе paint
А как комбобоксы/дейтедиты и текстедиты вставить?
Записан
igorko
Гость
« Ответ #3 : Октябрь 06, 2006, 13:05 »

Вот:
(Я не претендую на оригинальность и профессиональный код)
Буду благодарен всем за замечания и советы...

/*
    delegate.cpp

    A delegate that allows the user to change values from the model
    using different widgets.
*/

#include <QtGui>
#include <QtSql>

#include "delegate.h"
#include "mymodels.h"


MyDelegate::MyDelegate(QObject *parent)
: QItemDelegate(parent)
{
//   installEventFilter(this);
}

QWidget *MyDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem & option,
    const QModelIndex & index) const
{
   MySqlTableModel *m = (MySqlTableModel*)(index.model());

   if ( m->isForeignKey( index.column() ) )
   {
      QString query = QString ("SELECT %1 FROM %2") // ORDER BY %1")
            .arg( m->getForeignFieldName( index.column() ) )
            .arg( m->getForeignTableName( index.column() ) );

      QSqlQuery q(query);
      QStringList sl;
      while (q.next())
         sl += q.value(0).toString();

       MyComboBox *comboEditor = new MyComboBox(sl, parent);
      comboEditor->setObjectName("ComboEditor");
      comboEditor->installEventFilter(const_cast<MyDelegate*>(this));

      return comboEditor;
   }

   QDateEdit *dateEditor;
   QTextEdit *textEditor;
   QLineEdit *lineEditor;

   switch ( m->getFieldType( index.column() ) )
   {
      case QVariant::Date:
         dateEditor = new QDateEdit(parent);
         dateEditor->setDisplayFormat("dd.MM.yyyy");
         return dateEditor;
      case QVariant::String:
         if ( m->getFieldLength( index.column() ) == -1 )      // if length = -1  TEXT field
         {
            textEditor = new QTextEdit(parent);
            textEditor->setObjectName("TextEditor");
            return textEditor;
         }
   }

   return QItemDelegate::createEditor(parent, option, index);
}

void MyDelegate::closeEditor ( QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
{
   if(editor->objectName() == "ComboEditor")
      removeEventFilter(this);
   QItemDelegate::closeEditor(editor, hint);
}

void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
   MySqlTableModel *m = (MySqlTableModel*)(index.model());

   MyComboBox *comboBox;
   QDateEdit *dateEdit;
   QTextEdit *textEditor;
   QLineEdit *le;
   QString value;
   double d;

   if (m->isForeignKey(index.column()))
   {
         value = index.model()->data(index, Qt::DisplayRole).toString();
          comboBox = static_cast<MyComboBox*>(editor);
         comboBox->updateSearch(value);
         (const_cast<MyDelegate*>(this))->setOldValue (value);
         return;
   }

   switch ( m->getFieldType( index.column() ) )
   {
      case QVariant::Date:

         value = index.model()->data(index, Qt::DisplayRole).toString();
          dateEdit = static_cast<QDateEdit*>(editor);
         dateEdit->setDisplayFormat("yyyy-MM-dd");
         if (value != "") dateEdit->setDate(QDate::fromString(value, "yyyy-MM-dd"));
         else dateEdit->setDate (QDate::currentDate());
//         dateEdit->selectAll();
         return;

      case QVariant::String:
         if ( m->getFieldLength( index.column() ) == -1 )   // if length=-1 - we have text field
         {
            value = index.model()->data(index, Qt::DisplayRole).toString();
            textEditor = static_cast<QTextEdit*>(editor);
            textEditor->setPlainText(value);
            textEditor->selectAll();
            return;
         }
         le = static_cast<QLineEdit*>(editor);
         le->setText(index.model()->data(index, Qt::DisplayRole).toString());
         le->selectAll();
         return;

      case QVariant::Double:
      case QVariant::Int:
         d = index.model()->data(index, Qt::DisplayRole).toDouble();
         le = static_cast<QLineEdit*>(editor);
         le->setText(QString("%1").arg(d));
         le->selectAll();
         return;
   }
   return QItemDelegate::setEditorData(editor, index);
}

void MyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
   MySqlTableModel *m = (MySqlTableModel*)(index.model());

   QTableView *v = static_cast<QTableView*>(editor->parent()->parent());

   MyComboBox *comboBox;
   QDateEdit *dateEdit;
   QTextEdit *textEditor;
   QLineEdit *lineEditor;

   QString value;

   if (m->isForeignKey(index.column()))
   {
         comboBox = static_cast<MyComboBox*>(editor);
         value = comboBox->currentText();

         if (comboBox->isInFullList(value) == TRUE)
            model->setData(index, value);
         else
         {
            QMessageBox::information(editor,"MyDB", "В списку немає такого значення!");
            model->setData(index, oldValue);
         }
//         v->resizeColumnToContents(index.column());

         return;
   }

   switch ( m->getFieldType( index.column() ) )
   {
      case QVariant::Date:
         dateEdit = static_cast<QDateEdit*>(editor);
         value = dateEdit->text();
         model->setData(index, value);
         return;
      case QVariant::String:
         if ( m->getFieldLength( index.column() ) == -1 )   // if length = -1  TEXT field
         {
            textEditor = static_cast<QTextEdit*>(editor);
            value = textEditor->toPlainText();
            model->setData(index, value);
            return;
         }
   }

   return QItemDelegate::setModelData(editor, model, index);
}

void MyDelegate::updateEditorGeometry(QWidget *editor,
    const QStyleOptionViewItem &option, const QModelIndex &index) const
{
   MySqlTableModel *m = (MySqlTableModel*)(index.model());

   QWidget *w = static_cast<QWidget*>(editor->parent());

   QRect r = option.rect;
//   int h = w->size().height() - editor->rect().height()*index.row();
//   r.setSize(QSize(200,(100 > h)?h:100));

//   if ( m -> getFieldType( (index.column() ) == QVariant::String) && (m -> getFieldLength ( index.column() ) == -1 ) )
//      editor->setGeometry(r); // for TEXT field (length == -1)
//   else
      editor->setGeometry(option.rect);
}


bool MyDelegate::eventFilter(QObject *obj, QEvent *event)
{
   if (event->type() == QEvent::KeyPress)
   {
      QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
      if (keyEvent->key() == Qt::Key_Return)
      {
         if (obj->objectName() == "ComboEditor")
         {
            MyComboBox *comboBox = static_cast<MyComboBox*>(obj);
            if(comboBox->count() != 1)
            {
               comboBox->showPopup();
               return true;
            }
         }
         else
            if(obj->objectName() == "TextEditor")
            {
               QTextEdit *textEdit = static_cast<QTextEdit*>(obj);
               textEdit->insertPlainText("\n");
               return true;
            }
      }
   }
   return QItemDelegate::eventFilter(obj, event);
}
Записан
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  


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