Использование пользовательского типа данных в QT TreeModel - PullRequest
0 голосов
/ 24 апреля 2019

Это мое определение класса Container

class Container
{
private:
      std::string stdstrContainerName;
      std::string stdstrPluginType;
      std::string stdstrPluginName;
      int iSegments;
      float fRadius;
public:
    Container();
    explicit Container(std::string strContainerName , std::string 
    strPluginName , std::string strPluginType, int segments , float 
     radius  );
  ~Container();
  std::string GetName();
  std::string GetType();
   void SetName(std::string stdstrName);
};

Я хочу, чтобы узлы TreeView содержали объект класса Container как данные.

Это файл заголовка для класса TreeItem.

 class TreeItem
  {
  public:
    explicit TreeItem( const Container &data , TreeItem *parent = 0 );
   ~TreeItem();
    TreeItem *parent();
    TreeItem *child(int iNumber);
    int childCount() const;
    int childNumber() const;
    Container data() const;
    bool setData(const Container &data);
    bool insertChildren(int position, int count );
    bool removeChildren( int position  , int count );
private:
   QList<TreeItem*> childItems;
   Container itemData;
   TreeItem* parentItem;
};

Проблема, с которой я сталкиваюсь, заключается в реализации функций TreeModel.Как я могу использовать контейнер в качестве типа данных вместо QVariant.

     QVariant data(const QModelIndex &undex, int role) const override;
     QVariant headerData(int section, Qt::Orientation orientation,
     int role = Qt::DisplayRole) const override;
     bool setData( const QModelIndex &index , const QVariant &value , int 
     role = Qt::EditRole) override;

1 Ответ

2 голосов
/ 24 апреля 2019

Вы не можете использовать Container вместо QVariant, но вы можете использовать Container внутри QVariant.Посмотрите на Q_DECLARE_METATYPE.

Добавьте его в файл заголовка после объявления Container:

class Container
{
private:
    // ...
public:
    Container();
    // ...
};

Q_DECLARE_METATYPE(Container); // You only need this once, so here is a good place

Когда вы создали Containerметатип, вы можете вернуть его так:

QVariant data(const QModelIndex &index, int role) const override {
    TreeItem *item = ...;
    return QVariant::fromValue(item->data());
}

И, по вашему мнению, вы получите Container следующим образом:

QVariant v = model()->data(index, role);
Container c = v.value<Container>();

Остерегайтесь, что это работает только внутритот же поток, иначе вам нужно зарегистрировать Container с qRegisterMetaType() и, возможно, даже написать функцию конвертера из / в QVariant.
Это не относится к вашей ситуации, хотя, потому что модель и видне предназначены для жизни в разных темах.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...