PDA

View Full Version : [SOLVED] Promoted widget and constructor parameters



AlbertoN
24th October 2013, 11:35
Hi all,

I have this scenario:

I created a custom Database class, then I create an instance of it in main.cpp and i pass it across my app as a const pointer:



Database *const m_db = new Database();

m_db->createTables();
m_db->exampleData();

MyApp(m_db);

therefore my MyApp constructor is like this:



MyApp(Database *const m_db=0, QWidget *parent = 0);


Now I need to pass the Database pointer to a promoted widget. Is it possible?
When I try to do that I get an error as in designer Database class is not known, but as my pointer is const I can't call a
member method to set it, but rather I have to use a member initializer list, something like:



class Database;
class Widget : public QWidget
{
public:
Widget(Database *const db, QWidget *parent = 0) : QWidget(parent), m_db(db) {}

private:
Database *const m_db;
};


Is there any other option except to lose principle of least privilege or avoid using promoted widgets?
I tried googling, but I didn't find anything.

Thanks all

spirit
24th October 2013, 12:15
Add a setter to your Widget class which takes Database pointer.

AlbertoN
24th October 2013, 12:25
I can't use it.

A const pointer is like a constant and it can be setted into a class only in constructor's member initializer list:



MyClass::MyClass(const int foo)
: mfoo(foo) //<--member initializer list
{}


so my options as far as I know are:

1. lose principle of least privilege (this means does not use "const")
2. do not use promotion


Is there any other way?

spirit
24th October 2013, 12:32
Sorry, misread. :)

Yep, in that case it's easier to remove const.

AlbertoN
24th October 2013, 12:35
Ok thanks.

stampede
24th October 2013, 12:58
Consider using QSharedPointer (http://qt-project.org/doc/qt-5.0/qtcore/qsharedpointer.html) if you are sharing a resource between many objects.

anda_skoa
24th October 2013, 18:08
Alternative option is to add an empty widget to your UI in designer and add your widget as it child in code, thus being able to pass parameters to its constructor.

Cheers,
_