繁体   English   中英

通过指针传递QObject(Qt)

[英]Passing QObject with Pointer (Qt)

我的目标是将windowobject指针传递给另一个类。 我会告诉你我到目前为止所得到的。 其中:“对话框”是要传递的窗口。

主窗口

dialog = new Dialog(this);
someClass(dialog);

某班的Konstruktor

 someClass::someClass(Dialog *d)
 {
 Dialog *dia = d;
 }

someClass.h

#include "dialog.h"
...
public:
someClass(Dialog *dialog)
//Dialog d;

该程序现在运行,但是我不确定我是否达到了我想要的。 现在可以与我的对话框进行交互吗? 我想要的是这样的东西。

 dia->ui->lineEdit->setText();

任何帮助都将被申请

someClass(&dialog);

是不正确的...您有一个指针,并在函数中提供了指针的地址(指向该指针的指针)

你也有

Dialog d;

在标题中,并为其分配一个Dialog*

我建议您看看: The Definitive C ++ Book Guide and List

我们不知道您的Dialog类是什么样子,但是如果它的成员ui是public的(或者someClassDialog的朋友),那么您应该可以

dia->ui->lineEdit->setText();

你有编译器错误吗? 还是文字根本没有按预期显示? 您仍然需要使用来显示对话框

dia->show();

要么

dia->exec();

我的目标是将windowobject指针传递给另一个类。 我会告诉你我到目前为止所得到的。 其中:“对话框”是要传递的窗口。

考虑您的代码:

 someClass::someClass(Dialog *d)
 {
 Dialog *dia = d;
 }

是构造函数someClass中的本地成员。 因此,它仅在构造函数本身中具有作用域(在构造函数外部不可见,并且实际上,它不在构造函数外部(当构造函数超出范围时被销毁))。

幸运的是,dia是一个指针(对象的地址),而不是实际的对话框(因此,只有指针,而不是它指向的对象超出了范围)。 如果希望指针保留在作用域中以便以后访问,则必须将其“绑定”到类的作用域(使其成为类成员)。

class MyClass 
{
  public:
     //Using reference as it may not be null...
     MyClass( Dialog& dialog );

     void showDialog();

  private:
    //We only want to expose a small part of dialog to users, 
    // hence keep it private, and expose what we want through
    // the interface (the public part).
    Dialog& dialog_;
};

//MyClass.cpp

MyClass::MyClass( QPointer<Dialog> )
: dialog_( dialog ) //Google "member initialisation"
{
}

void MyClass::showDialog(){ dialog_.show(); }

-----修改/附加答案-----

如果在上面的示例中dialog_是可选的,则您不必使其成为引用成员,因为引用成员需要初始化(一个成员不能具有未初始化的引用)。 在这种情况下,使其成为指针...使用Qt时,我将其设为QPointer(假定对话框是QObject),因为QPointers比原始指针更安全(至少始终初始化为零)。 。

我将向您展示使它保持简单的基本原理。 全面了解QPointers和智能指针。

例如:

class MyClass 
{
  public:
     // May or may not hold zero...
     explicit MyClass( Dialog* dialog = 0 );

     void showDialog();

  private:
    //We only want to expose a small part of dialog to users, 
    // hence keep it private, and expose what we want through
    // the interface (the public part).
    Dialog* dialog_;
};

//.cpp
MyClass::MyClass( Dialog* dialog /* = 0*/ )
: dialog_( dialog )
{
}

void MyClass::showDialog() 
{
  if( dialog_ ) 
  {
    dialog_->show();
  }
  else
  {
    std::cout << "This is in fact not a dialog"
                 "\nbut be so kind as to enter"
                 " whatever you want here ;-)" 
              << std::endl;

    while( !terminated() )
    {
      std::string inputStr;
      std::cin >> inputStr;
      evalute( inputStr );
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM