c++ - Qt访问类中的mainWindow而不给它对象

标签 c++ qt class oop object

我需要在其他类中访问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
}

我认为这是不可能的,但是我尝试一下...
感谢您的回答!

最佳答案

I need to access the mainWindow object in a different class. The problem is, that I can not give mainWindow to this class (I don't want to do this, it would make everything much more complicated).



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

Is there any way in C++ or Qt to put an object in something like a local "database" or sth where every other class in the project can look into and communicate with the objects.



本地线程存储是一种实现此类目标的已知模式。 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;
}

在LTS中注册主窗口对象:
#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();

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

关于c++ - Qt访问类中的mainWindow而不给它对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040743/

相关文章:

c++ - 使用 Qt 测量过程的实际运行时间

python - 占位符文本未显示(pyside/pyqt)

java - 创建简单的学生类

c++ - 以特定格式读取文件

c++ - const 丢弃限定符 c++

c++ - Qt5 在多宿主网络上绑定(bind) TCP 套接字

Python/C-API : Add class to module

PHP 类未正确回显

c++ - 为什么 OSX Mavericks 不编译我的 GLSL 着色器?

c++ - 返回迭代器似乎使它无效