ドキュメント

View Categories

コンポーネントを作成する

1 min read

ソフトウェア-GUI3で説明したとおりコンポーネントを簡単に作成することができます。ここではC++でコンポーネントを作成するときの解説を追加で説明します。

my_component.hpp

class MyComponent : public Component
{
public:
 // modには共通データstoreやdrawerなど共通して使用するオブジェクトのポインタが入ってます。
  MyComponent(MOD mod)
  {
    box = std::make_unique<BoxComponent>(
        mod 
      , [width]
      , [height]
      , spa::box::POS::[VALUE]);

    image = std::make_unique<ImageComponent>(
        mod
      , [filepath]);
  }

  ~MyComponent() = default;

  // コピーコンストラクタ、box、imageをコピー
  MyComponent(MyComponent const& other)
    : Component(mod)
    , box{ std::make_unique<BoxComponent>(*other.box) }
    , image{ std::make_unique<ImageComponent(*other.image) }
  {}

  // コピー演算、box、imageをコピー
  MyComponent& operator(MyComponent const& other)
  {
    Component::operator=(mod);
    *box = *other.box;
    *image = *other.image;
    return *this;
  }

  // thisにboxをアタッチ、boxにimageをアタッチします。
  void configure()
 {
    attach(box.get());
    box->attach(image.get());
  }

private:
  std::unique_ptr<BoxComponent> box;
  std::unique_ptr<ImageComponent> image;
};
ソフトウェア-GUI3https://amateru-kami.online/software/gui3


std::unique_ptrはスマートポインタと呼ばれ、オブジェクトが破棄される時に自動でリソースが解放されるポインタです。ただし、コピー不可なのでリソースを指すポインタ変数は1つだけとなります。他にstd::shared_ptrもあります。std::shared_ptrは参照カウンタを持っており、参照カウンタが0になるとリソースが解放されます。std::unique_ptrの方が高速なので所有権が明確な場合は優先して使うと良いと言われています。

std::unique_ptrはコピーが不可なのでそのポインタを所有するオブジェクトをコピーする場合、コピーコンストラクタ、コピー演算にstd::unique_ptrの扱いを指定する必要があります。std::unique_ptr以外のプロパティも漏れがないように指定する必要があります。

実際にコピーコンストラクタ、コピー演算が必要な場合があります。FcComponent(std::function)を使ってコンポーネントをコピーする場合や、std::listに格納する場合、コピーコンストラクタを呼び出します。

GUI3ではComponentのコピーは可能ですが、attachはコピーを含め複数回行わないように注意してください。

GUI3ではIndexComponent→AppComponentの順で構成します。

IndexComponentは実行ファイルから動的ロードされるコンポーネントです。IndexComponentからAppComponentがattachされます。作成したコンポーネントはAppComponentにattachして表示します。

AppComponentにMyComponentを追加します。

// app_component.hpp
#pragma once

#include <gui/components/component.hpp>
// オリジナルコンポーネントを読み込み
#include <[path to my_component.hpp]>

class AppComponent : public Component
{
public:
  AppComponent(MOD mod);

  ~AppComponent() = default;

  AppComponent(AppComponent const&);
  AppComponent& operator=(AppComponent const&);

  void configure();

private:
  // オリジナルコンポーネントを追加
  FcComponent my_component;
};

// app_component.cpp
#include <gui/components/app_component.hpp>

AppComponent::AppComponent(MOD mod)
  : Component(mod)
{
  // 作成したMyComponentで初期化します。
  my_component = MyComponent(mod);
}

AppComponent::AppComponent(AppComponent const& other)
  : Component(other)
{
}

AppComponent& AppComponent::operator=(AppComponent const& other)
{
  Component::operator=(other);
  return *this;
}

void AppComponent::configure()
{
  // my_componentをattachします。
  attach(my_component);
}
ソフトウェア-GUI3https://amateru-kami.online/software/gui3


複数画面を遷移するアプリケーションの場合は、PageComponentをattachしてSPA(Single Page Application)を作成していきます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です