Qt访问类中的mainWindow而不向其提供对象

Qt access mainWindow in a class without giving the object to it

本文关键字:对象 访问 mainWindow Qt      更新时间:2023-10-16

我需要访问另一个类中的mainWindow对象。问题是,我不能给这个类提供mainWindow(我不想这样做,这会让一切变得更加复杂)。问题:在C++或Qt中,是否有任何方法可以将一个对象放在本地"数据库"或其他东西中,让项目中的其他类都可以查看并与对象通信。我最终想要的是这样的东西:

// A.h
#ifndef A_H
#define A_H
class A{
public:
A() { /*here comes the ting*/ myMainWindow->sayHi(); }
};
#endif // A_H

// MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "a.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
A *a = new A;
}
MainWindow::~MainWindow(){delete ui;}
MainWindow::sayHi(){
// just do anything
}

我不认为,这是可能的,但我尝试一下。。。谢谢你的回答!

我需要访问另一个类中的mainWindow对象。这个问题是,我不能给这个类mainWindow(我不想这样做会使一切变得更加复杂)。

这是可行的。作者不想公开"主窗口"变量,该变量包含对象的引用或指针。而且,显然作者希望UI对象可以从其他对象中调用。在Qt中,这意味着UI线程上的两个对象或通信仅通过排队的信号槽连接。但是直接调用需要,因此在同一线程上。

在C++或Qt中有什么方法可以把对象放在类似本地"数据库"或项目中其他类都可以观察物体并与之交流。

本地线程存储是实现类似功能的已知模式。Qt有自己的实现,称为QThreadStorage。你可以尝试这样的东西:

// myLts.h
void ltsRegisterObject(const QString &key, QObject *object);
void ltsRemoveObject(const QString &key);
QObject* ltsGetObject(const QString &key);
template <typename T> T* ltsGet(const QString &key) {
return qobject_cast<T*>(ltsGetObject(key));
}

// myLts.cpp
static QThreadStorage<QMap<QString, QObject*> > s_qtObjects;
void ltsRegisterObject(const QString &key, QObject *object)
{
s_qtObjects.localData().insert(key, object);
}
void ltsRemoveObject(const QString &key)
{
if (!s_qtObjects.hasLocalData())
return;
s_qtObjects.localData().remove(key);
}
QObject* ltsGetObject(const QString &key)
{
QObject *object;
auto it = s_qtObjects.localData().find(key);
return it != s_qtObjects.localData().end() ? it.value() : nullptr;
}

在TTS:中注册主窗口对象

#include "myLts.h"
// ...
// register main window in LTS
ltsRegisterObject("mainWindow", &mainWindow);

查找并使用对象:

#include "myLts.h"
// ...
// use main window from LTS
auto* pMainWnd = ltsGet<QMainWindow>("mainWindow");
if (pMainWnd)
pMainWnd->show();

附言:我没有编译这个。但如果是这样的话,修复起来并不难