Qt GUI 从另一个 class 访问 MainWindow 的最简单方法

Qt GUI Easiest way to access MainWindow from another class

我正在做一个 21 点程序,我在另一个 class ("hand.h") 中跟踪玩家手中的牌,而不是主要的 window class .

在手牌 class 中,对于我收集的每张牌,我还创建了一个 QLabel,它为牌抓取正确的牌图像,并设置牌应该出现在主画面上的坐标window。

问题是我无法基于最初在 main 函数中创建的 MainWindows 对象创建 QLabel。有什么简单的方法可以让我很容易地获得这些信息吗?感谢您的帮助!

我试过使用 QGuiApplication::topLevelWindows(),但运气不好。这是我正在使用的函数。

    #include <QRect>
    #include <QApplication>
    #include <iostream>
    #include <QLabel>
    #include "mainwindow.h"
    #include <QMainWindow>
    #include <QWindowList>
    #include <QWidgetList>
    #include "ui_mainwindow.h"

    void Test() {

    QList<QWindow*> Main_Window = QGuiApplication::topLevelWindows();
     for (int i = 0; i < Main_Window.size(); ++i) {
        if(Main_Window.objectName() == "mainWindow") // name is OK
                break;
        }
    QMainWindow* mainWindow = static_cast<QMainWindow*>(Main_Window);


    QLabel* temp;
    temp = new QLabel(Main_Window);
    temp->setPixmap(QString("Ten of Clubs.png"));
    temp->setGeometry(290, 300, 350, 390);
    temp->show();

    }

这是创建主window

的main.cpp文件
    int main(int argc, char *argv[])
    {
      srand(time(NULL));
      QApplication a(argc, argv);
      MainWindow w;

      w.show();
      return a.exec();
    }

我在网上找到了迭代代码,但一直遇到问题。 我在尝试遍历列表时遇到问题,但我不知道如何识别列表,并且错误提示没有 objectName() 函数。此外,在静态转换行中,有一个错误表明我无法将 QList 转换为 QMainWindow 类型。任何帮助将不胜感激。

一般情况下没有办法,因为某些应用程序可能有 几个(顶层)QMainWindow-s(它们的列表可能会随时间变化)。因此,对于这种情况,您最好明确地将指针传递给它(您要处理的特定 QMainWindow)....

一种可能的方法是让 QApplication (which is a singleton class, see QCoreApplication::instance 的特定 subclass 获得它的唯一实例)并在您的应用程序 subclass 中作为字段放置显式 windows 你想要处理(也许你甚至想在你的应用程序中添加一些新的信号或插槽 class)。

但是,您可以使用 QGuiApplication::topLevelWindows() or QGuiApplication::allWindows() to get the list of all such windows. Notice that a QWindowList is just a QList<QWindow *>. So see QList 来了解如何遍历或迭代该列表。

一旦找到所需的 QMainWindow,通常的做法是在其中添加 QLabel(但同样,信号和槽可能会有所帮助)。

顺便说一句,每个(显示的)小部件都有其 window,参见 QWidget::window()


关于您的代码:

你的 Main_Window 的名字真的很糟糕(这个名字太混乱了,我无法使用它)。它是 列表 而不是 window。所以先打码:

QMainWindow* mainWindow = nullptr;
{
  QList<QWindow*> topwinlist = QGuiApplication::topLevelWindows();
  int nbtopwin = topwinlist.size();
  for (int ix=0; ix<nbtopwin; ix++) {
    QWindow*curwin = topwinlist.at(ix);
    if (curwin->objectName() == "mainWindow")
      mainWindow = dynamic_cast<QMainWindow*>(curwin);
  }
} 

我没有测试上面的代码,我不确定它是否正确,甚至不能编译。但是你为什么不只是有一个全局指针指向你的 main window:

 MainWindow*mymainwinp = nullptr;

并在你的 main 正文中适当地初始化它:

int main(int argc, char *argv[]) {
  srand(time(NULL));
  QApplication a(argc, argv);
  MainWindow w;
  mymainwinp = &w;
  w.show();
  int r = a.exec();
  mymainwinp = nullptr;
  return r;
}

然后在其他地方使用 mymainwinp(例如在您的 Test 中)?如果您想要更优雅的代码,请定义您自己的 QApplication 的 subclass 并将 mymainwinp 作为其中的一个字段。