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

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

Страниц: [1]   Вниз
  Печать  
Автор Тема: [Решено] Отображение картинки в QTableView  (Прочитано 6553 раз)
vunder
Гость
« : Ноябрь 01, 2011, 10:27 »

У меня есть модель. В первой колонке она возвращает картинку, в остальных - текст. Проблема в том, что картинка отображается серой, т.е. как будто элемент запрещен (рис. 1). Если отобразить эту же картинку во всех столбцах, то в других она отображается нормально.

Код
C++ (Qt)
#ifndef FHSSRESULTMODEL_H
#define FHSSRESULTMODEL_H
 
#include <QAbstractTableModel>
#include <QDateTime>
#include <QVector>
#include <QStringList>
 
class FHSSResultModel : public QAbstractTableModel
{
   Q_OBJECT
public:
   struct FHSSStatus
   {
   public:
       FHSSStatus() {}
       FHSSStatus(int i, qint64 f, qint64 b, QDateTime d, double p, double dr,
                  double q, int fs, int sb, int dn, int s) :
           id(i), base(f), band(b), begTime(d), power(p), dir(dr), qual(q),
           freqstep(fs), sampleband(sb), duration(dn), state(s) {}
 
       int id;
       qint64 base;
       qint64 band;
       QDateTime begTime;
       double power;
       double dir;
       double qual;
       int freqstep;
       int sampleband;
       int duration;
       int state;
   };
 
   explicit FHSSResultModel(QObject *parent = 0);
   QVariant data(const QModelIndex &index, int role) const;
   int rowCount(const QModelIndex &parent) const;
   int columnCount(const QModelIndex &parent) const;
   QVariant headerData(int section, Qt::Orientation orientation, int role) const;
   Qt::ItemFlags flags(const QModelIndex &index) const;
 
public slots:
   void prepareResults();
   void tableResult(int id, qint64 base, qint64 band, QDateTime begTime,
                    double power, double dir, double qual, int freqstep,
                    int sampleband, int duration, int state);
   void finalizeResults();
   void clearResults();
 
private:
   QVector<FHSSStatus> results;//Current results
   QVector<FHSSStatus> tmp_results;//Temporary results, while model is collecting data
   QStringList headers;
};
 
#endif // FHSSRESULTMODEL_H
 

Код
C++ (Qt)
#include "fhssresultmodel.h"
#include "fhssorder.h"
#include <QIcon>
 
FHSSResultModel::FHSSResultModel(QObject *parent) :
   QAbstractTableModel(parent)
{
   headers << trUtf8(" ") << trUtf8("Ц.част., МГц") << trUtf8("Полоса, кГц")
           << trUtf8("Шаг, кГц") << trUtf8("Ур., дБ") << trUtf8("Пеленг, град")
           << trUtf8("Кач., %") << trUtf8("Вр.начала") << trUtf8("Длит., с");
}
 
QVariant FHSSResultModel::data(const QModelIndex &index, int role) const
{
   if (!index.isValid())
   {
       return QVariant();
   }
   switch (role)
   {
   case Qt::DisplayRole:
       switch (index.column())
       {
       case 1:
           return QString::number(results[index.row()].base / 1e6, 'f', 3);
           break;
       case 2:
           return QString::number(results[index.row()].band / 1e3, 'f', 0);
           break;
       case 3:
           return QString::number(results[index.row()].freqstep / 1e3, 'f', 0);
           break;
       case 4:
           return QString::number(results[index.row()].power, 'f', 0);
           break;
       case 5:
           return QString::number(results[index.row()].dir, 'f', 1);
           break;
       case 6:
           return QString::number(results[index.row()].qual, 'f', 0);
           break;
       case 7:
           return results[index.row()].begTime.toString("hh:mm:ss");
           break;
       case 8:
           return QString::number(results[index.row()].duration / 1e3, 'f', 2);
           break;
       default:
           return QVariant();
       }
       break;
   case Qt::BackgroundColorRole:
       if (results[index.row()].state & FHS_WORKING)
           return Qt::red;
       else if (results[index.row()].state & FHS_MANUAL_ADD)
           return Qt::magenta;
       else
           return Qt::white;
       break;
   case Qt::DecorationRole:
       if (index.column() == 0)
       {
           if (results[index.row()].state & FHS_WRITING_SIG)
               return QIcon(trUtf8(":/save_queue.ico"));
           else if (results[index.row()].state & FHS_NOW_WRITING)
               return QIcon(trUtf8(":/saving.ico"));
           else
               return QVariant();
       } else
           return QVariant();
       break;
   default:
       return QVariant();
   }
}
 
int FHSSResultModel::rowCount(const QModelIndex &) const
{
   return results.count();
}
 
int FHSSResultModel::columnCount(const QModelIndex &) const
{
   return headers.count();
}
 
QVariant FHSSResultModel::headerData(int section, Qt::Orientation orientation, int role) const
{
   if (role != Qt::DisplayRole)
   {
       return QVariant();
   }
   return (orientation == Qt::Horizontal) ? headers[section] : QVariant();
}
 
Qt::ItemFlags FHSSResultModel::flags(const QModelIndex &index) const
{
   Qt::ItemFlags flags = QAbstractTableModel::flags(index) | Qt::BackgroundColorRole;
   if (index.isValid() && (index.column() == 0))
       flags = flags & Qt::DecorationRole;
   return index.isValid() ? (flags & ~Qt::ItemIsEditable) : flags;
}
 
void FHSSResultModel::prepareResults()
{
   tmp_results.clear();
}
 
void FHSSResultModel::tableResult(int id, qint64 base, qint64 band,
                                 QDateTime begTime, double power, double dir,
                                 double qual, int freqstep, int sampleband,
                                 int duration, int state)
{
   tmp_results.append(FHSSStatus(id, base, band, begTime, power, dir, qual,
                                 freqstep, sampleband, duration, state));
}
 
void FHSSResultModel::finalizeResults()
{
   results.clear();
   results << tmp_results;
   tmp_results.clear();
   emit layoutChanged();
}
 
void FHSSResultModel::clearResults()
{
   results.clear();
   tmp_results.clear();
   emit layoutChanged();
}
 
« Последнее редактирование: Ноябрь 01, 2011, 11:30 от vunder » Записан
ddrtn
Гость
« Ответ #1 : Ноябрь 01, 2011, 10:33 »

Код:
 flags = flags & Qt::DecorationRole;

Чего-то это не правильно. причем тут Qt::DecorationRole;
Записан
vunder
Гость
« Ответ #2 : Ноябрь 01, 2011, 10:37 »

Код:
 flags = flags & Qt::DecorationRole;

Чего-то это не правильно. причем тут Qt::DecorationRole;
Задаю Qt::DecorationRole, чтобы указать, что в данных будет картинка
Цитировать
Qt::DecorationRole    1    The data to be rendered as a decoration in the form of an icon. (QColor, QIcon or QPixmap)
Записан
ddrtn
Гость
« Ответ #3 : Ноябрь 01, 2011, 10:55 »

Код:
enum Qt::ItemFlag
{
     NoItemFlags = 0,
     ItemIsSelectable = 1,
     ItemIsEditable = 2,
     ItemIsDragEnabled = 4,
     ItemIsDropEnabled = 8,
     ItemIsUserCheckable = 16,
     ItemIsEnabled = 32,
     ItemIsTristate = 64
};
Записан
ddrtn
Гость
« Ответ #4 : Ноябрь 01, 2011, 10:57 »

Qt::ItemRole здесь никак. складываешь котов со стульями.
Записан
vunder
Гость
« Ответ #5 : Ноябрь 01, 2011, 11:30 »

Qt::ItemRole здесь никак. складываешь котов со стульями.
Действительно, коты со стульями... Спасибо
Записан
Страниц: [1]   Вверх
  Печать  
 
Перейти в:  


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