【发布时间】:2017-02-18 00:44:55
【问题描述】:
我正在做一个二十一点程序,并且我在主窗口类之外的另一个类(“hand.h”)中跟踪玩家手中的牌。
在手牌类中,对于我收集的每张卡片,我还创建了一个 QLabel,它为卡片抓取正确的卡片图像,并设置卡片应出现在主窗口上的位置的坐标。
问题是我无法根据最初在 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();
}
这里是创建主窗口的 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 类型。任何帮助将不胜感激。
【问题讨论】:
-
你能解释一下如何使用 QLabel 来使用 topLevelWindows() 吗?我曾多次尝试使用它,但没有任何运气。除了 main 函数中的预制窗口之外,我没有创建任何窗口。
-
这应该进入你的问题(你应该编辑)。如果您的代码在 github 上,您可以在问题中提供指向它的链接。
-
你是对的。我很抱歉。我已经用我的代码更新了它并尝试解决它。再次感谢您的帮助!
-
我尝试迭代列表并没有成功。有什么建议吗?
-
这不是 Qt 特有的问题:像对待任何其他需要引用其他对象的 C++ 类一样处理它。