2011-11-09 67 views
0

我有两个部件:Qt的C++访问属性

class Widget: public QWidget 
{ 
    public: 
    Button* button; 
    Widget(); 
    int value; // need to get this var 
} 

Widget::Widget() 
{ 
    button = new Button(this); 
} 


class Button: public QPushButton 
{ 
    public: 
    Button(QWidget* parent = 0); 
} 

Button::Button(QWidget* parent) : QPushButton(parent) 
{ 
    this->parentWidget()->value // dont see var 
} 

如何,我可以看到从父窗口小部件属性?什么是最好的方法来做到这一点?由于

+0

你的意思是什么可以看到?在你的编辑器(智能感知) - 在屏幕上? – mbx

+0

抱歉不准确。我的意思是可以访问变量 – Outsider

回答

1

您的按钮构造可以采取的,而不是一个QWidget一个Widget:

class Button: public QPushButton 
{ 
public: 
    Button(Widget* parent = 0); 
} 

Button::Button(Widget* parent) : QPushButton(parent) 
{ 
    parent->value = 0; 
} 
+0

它不起作用:'class QWidget'没有名为'value'的成员。 – Outsider

+0

@Ramix:您是否注意到该参数的类型是'Widget *',而不是'QWidget *'? – Bill

0

你有两个选择

变化

Button::Button(QWidget * parent) 
{ 
} 

TO

Button::Button(Widget * parent) 
{ 
    //Here class type is already known 
    parent->value; 
} 

或者

使用的static_cast <的Widget *>(父)在构造函数中投到类,如果你肯定知道它始终将是如此。否则,使用dynamic_cast的<的Widget *>(父)

Button::Button(QWidget * parent) 
{ 
    Widget* wparent = static_cast<Widget*>(parent); 
    //now your can access wparent member variables 
} 
0

确保您使用Q_OBJECT宏。然后你可以使用property system。它不打算直接访问QWidget的成员。他们甚至不能以这种方式连接 - 当然你可以强制你的按钮使用(只)你的Widget类,但这会导致紧耦合。

0

如果只是在构造函数中需要它,为什么不把它作为参数传递呢?

class Button: public QPushButton 
{ 
public: 
    Button(int value, QWidget* parent = 0); 
} 

如果需要它的地方以外的构造,这将是非常有益知道这个值在做什么。它改变了外观吗?它是否在改变行为?我问,因为大多数允许你直接访问父母的方法会将你的小部件绑定到它的父项,对我来说,似乎有更好的方法来设计它。

例如,如果value在父级中以某种重要方式进行更改,请调用按钮类中的方法以通知其更改。这样,只要他们调用正确的方法,任何人都可以使用按钮类。

class Button: public QPushButton 
{ 
public: 
    Button(int value, QWidget* parent = 0); 

    void updateValue(int value); 
private: 
    int value; 
} 
0

我觉得只是一个类型转换就可以了:

Button::Button(QWidget* parent) 
{ 
    cout<<((Widget*)(this->parentWidget())->value; //print parent's value 
} 

然而,你的代码的逻辑是奇怪的:当你创建Widget实例,Button的构造函数将被调用首先,检索Widget的值。但是,Widget类尚未构建,因此值未初始化。