0

I'm fighting with Qt. Cannot find out reliable solution for my specific problem.

We have custom class MyWidget that must:

  • be derived from QWidget to override closeEvent method
  • have fields that must be initialzed in constructor

Problems:

  • QWidget's guts initialized with QUiLoader from .ui file. So I have only QWidget* pointer
  • QWidget is non-copyable.
  • QWidget has no move constructor

The code (error checking and memory management are omitted for simplicity):

class MyWidget : public QWidget
{
    bool m_Closed;
public:
    MyWidget(QWidget* qw) : 
        QWidget(*qw), // error: copy constructor is private
        m_Closed(false)
    {}

    bool IsClosed() const { return m_Closed; }

    virtual void closeEvent(QCloseEvent *) override { m_Closed = true; }
};

QFile file("main.ui");
QUiLoader uiLoader;
MyWidget* uiMain = new MyWidget(uiLoader.load(&file));
uiMain->show();

Questions:

  • How can I workaround this? I feel that solution is very simple.
  • Can I use move semantics here somehow?

Note that:

  • I cannot make QWidget member, as I need to override its method.
  • Probably, I can make some MyWidget::Init() method, to init those bool flag, which must be called after each instantiation. But I find this solution unreliable.
  • In the end, I must just have QWidget, that I can check if it was closed or not (maybe you know another, simple way)
  • I use MSVC 2013 RC and GCC 4.8.1, so C++11 solution would be great

Do not hesitate, I appreciate any suggestions and criticism.

Ivan Aksamentov - Drop
  • 12,860
  • 3
  • 34
  • 61

1 Answers1

1

.ui files can use custom classes that derive from QWidget, so you can use your class in the Designer - even without writing any Designer plugins (it won't be shown). Right-click on a widget and select "Promote".

You need to create your own derived version of QUiLoader, and provide an implementation of the factory method QUiLoader::createWidget that can create your widgets. See this answer for a complete example.

Then you put your initialization code in the derived widget.

Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313