传递带指针的QObject(Qt)

Passing QObject with Pointer (Qt)

本文关键字:Qt QObject 指针      更新时间:2023-10-16

我的目标是将windowobject指针传递给另一个类。我会向你展示我目前为止的成果。其中:"对话框"是要通过的窗口。

主窗口.cpp

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*

我建议你看一看:最终C++图书指南和列表

我的目标是将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(假设Dialog是QObject),因为QPointer比原始指针更安全(至少它们总是初始化为零)。

我将向您展示目前保持简单的基本原则。阅读有关QPointer和智能指针的一般信息。

例如:

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 );
    }
  }
}

我们不知道你的Dialog类是什么样子的,但如果它的成员ui是公共的(或者someClassDialog的朋友),那么你应该能够进行

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

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

dia->show();

dia->exec();