Qt访问类中的mainWindow而不向其提供对象
Qt access mainWindow in a class without giving the object to it
我需要访问另一个类中的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();
附言:我没有编译这个。但如果是这样的话,修复起来并不难
相关文章:
- 按基类对象访问派生类资源时出错
- 使用基类对象访问派生的仅类方法
- 从 const 对象访问非 const 方法
- 如何在C++中使用类对象访问指针数据成员
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 为什么引用类型在使用临时对象访问时是左值
- 从父对象 c++ 访问子方法
- 无法通过指针或对象 c++ 访问受保护的成员
- 为什么可以从类中的对象访问类的私有变量
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- 通过无符号 char 别名进行对象访问,加载和存储时会发生什么?
- 从对象访问结构枚举
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- 在C 中,可以从第三个共享对象访问其他两个不同共享对象
- 如何在C 中提供一个可呼叫的对象访问,例如lambda
- C 向量对象访问
- C++是否可以从同级第二个派生对象访问第一个派生对象的受保护基础数据成员?
- 如何从类内实例化的对象访问私有变量
- 多态性:通过类文本或对象访问静态成员