Yattabyte
Yattabyte

Reputation: 1480

Qt Extending my own widget

To put it simply, I want a new class that extends a custom widget that I've made, and thus have full access to it's UI.

I've tried several different methods so far based on how one would normally subclass/extend classes, but I'm somehow failing horribly for so many different reasons.

Additionally, simply using my widget as a member in my new class wouldn't do for this situation.

Can someone illustrate a quick example of how I would do this? I have done a bunch of searching but I can't seem to find any hits relating to exactly what I'm trying to do If all else fails I will simply copy over the code and make an actual new widget, which technically would have saved me lots time, but it just doesn't feel right doing that.

My first instinct was to do something like this ( Qwe being my new class, Asd being the widget ):

class Qwe : Asd {public: ...}

And I even made the widget's Ui public, but then I just got the error :

use of undefine type Ui::Asd

whenever I tried to access the Ui's elements.

Upvotes: 0

Views: 2155

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

Let's say we have a custom widget named BaseWidget and a child widget named ChildWidget. Declare BaseWidget as usually, but make its ui member protected instead of private, like this:

protected:
  Ui::BaseWidget *ui;

Declare ChildWidget as an ordinary widget derived from BaseWidget. Make sure you include ui_BaseWidget.h in the ChildWidget.cpp file, just as you do it in BaseWidget.cpp (this include and the header itself is generated by Qt).

Header:

#include "BaseWidget.h"

class ChildWidget : public BaseWidget {
  Q_OBJECT
public:
  explicit ChildWidget(QString text, QWidget *parent = 0);    
};

Source:

#include "ChildWidget.h"
#include "ui_BaseWidget.h"

ChildWidget::ChildWidget(QString text, QWidget *parent) :
  BaseWidget(parent)
{
  ui->label->setText(text);
}

Upvotes: 2

Related Questions