Qt4父指针用法
我在理解 QT4 中 parent
指针的用法时遇到一些问题。
class firstClass : public QWidget
{
Q_OBJECT
public:
firstClass(QWidget *parent = 0);
~firstClass();
void doSomething();
private:
secondClass * myClass;
};
class secondClass : public QWidget
{
Q_OBJECT
public:
secondClass(QWidget *parent = 0);
void doSomethingElse();
};
我想在运行 doSomethingElse()
时调用 doSomething()
方法。有没有办法使用 parent
指针来做到这一点?
我尝试了 parent->doSomething()
但它不起作用。看起来 Qt Creator 只建议在 parent->
之后使用 QObject 类的方法。
另一方面,我不能像 secondClass(firstClass *parent = 0);
这样写 - 编译器返回错误:
感谢您的任何建议。
I'm having some problem with understanding usage of parent
pointer in QT4.
class firstClass : public QWidget
{
Q_OBJECT
public:
firstClass(QWidget *parent = 0);
~firstClass();
void doSomething();
private:
secondClass * myClass;
};
class secondClass : public QWidget
{
Q_OBJECT
public:
secondClass(QWidget *parent = 0);
void doSomethingElse();
};
I want to call doSomething()
method while running doSomethingElse()
. Is there any way to do it using parent
pointer?
I tried parent->doSomething()
but it doesn't work. It seems that Qt Creator is suggesting only methods from QObject class after parent->
.
On the other hand I can't write it like secondClass(firstClass *parent = 0);
- compilator returns error:
Thanks for any suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确信
secondClass
的父级始终是firstClass
那么您可以这样做:或者您可以使用
qobject_cast
并检查确保parent
实际上是firstClass
的实例:If you are positive that the parent of
secondClass
is always going to befirstClass
then you can do this:Alternatively you can use
qobject_cast
and check to make sure thatparent
is actually an instance offirstClass
:更类似于 Qt 的方法是使用信号和槽,而不是尝试直接调用不同的函数。
The more Qt-ish way to do this would be to use signals and slots, instead of trying to directly call a different function.