库需要QApplication。如何在Qt Quick项目中使用QApplication?

6

我有一个Qt Quick项目,刚刚添加了一些源文件。在尝试构建时,我收到以下错误消息:

QWidget: Cannot create a QWidget without QApplication

由于我有一个Qt Quick项目,我使用QGuiApplication。QApplication是QGuiApplication的子类。如何使QApplication可用于新添加的源代码?或者当Qt Quick和QWidget同时使用时,如何解决这个问题?

源文件是显示图形的QCustomPlot库。

编辑:

main.cpp:

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QtQuick2ApplicationViewer viewer;

    //Register C++ classes with QML
    qmlRegisterType<Bluetooth>("Bluetooth", 1, 0, "Bluetooth");

    //Set start QML file
    viewer.setMainQmlFile(QStringLiteral("qml/test/main.qml"));

    //New Code:
    // generate some data:
    QWidget widget;
    QCustomPlot * customPlot = new QCustomPlot(&widget);

    QVector<double> x(101), y(101); // initialize with entries 0..100
    for (int i=0; i<101; ++i)
    {
      x[i] = i/50.0 - 1; // x goes from -1 to 1
      y[i] = x[i]*x[i]; // let's plot a quadratic function
    }
    // create graph and assign data to it:
    customPlot->addGraph();
    customPlot->graph(0)->setData(x, y);
    // give the axes some labels:
    customPlot->xAxis->setLabel("x");
    customPlot->yAxis->setLabel("y");
    // set axes ranges, so we see all data:
    customPlot->xAxis->setRange(-1, 1);
    customPlot->yAxis->setRange(0, 1);
    customPlot->replot();

    //New Code End

    //Show GUI
    viewer.showExpanded();

    return app.exec();
}

错误:

QML debugging is enabled. Only use this in a safe environment.
QWidget: Cannot create a QWidget without QApplication
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.

在创建任何QWidgets之前,您必须先创建QApplication实例。 - drescherjm
@drescherjm:我可以在main()函数中同时使用QApplication和QGuiApplication循环吗? - uniquenamehere
不,我的意思是在创建任何QWidgets之前先创建你的QGuiApplication实例。 - drescherjm
@drescherjm:按照我在问题中编辑的方式仍然出现错误。 - uniquenamehere
@Phataas,你现在遇到了哪个错误?是同一个还是不同的?你能展示一些你正在做的代码吗? - Digital_Reality
显示剩余2条评论
1个回答

4

关键概念是QWidget::createWindowContainer()。尝试下面的代码:

#include <QQuickView>


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQuickView *view = new QQuickView();
    QWidget *container = QWidget::createWindowContainer(view, this);
    container->setMinimumSize(200, 200);
    container->setMaximumSize(200, 200);
    container->setFocusPolicy(Qt::TabFocus);
    view->setSource(QUrl("qml/test/main.qml"));
    ...
 }

您可以在以下帖子中找到详细信息:

介绍 QWidget::createWindowContainer()

使用 QWidget::createWindowContainer() 结合 Qt Widgets 和 QML


谢谢,这看起来非常有前途。我还没有测试过,但这正是我在寻找的。我也在你提供的链接中读到,这在Android上不起作用。我没有在我的问题中指定这一点,但Android是我正在开发的平台之一。从我所读的内容来看,这是不可能的,因为在Android上只能使用一个OpenGL表面(至少在Qt 5.1上,不知道在Qt 5.2中是否已经修复)。如果您对如何解决这个问题有任何建议,请随时在下面评论。我会尝试并查看它是否仍然有效。(祈求好运) - uniquenamehere
1
我曾经遇到同样的问题。我的解决方案很简单,只是使用QApplication而不是QGuiApplication。现在一切都完美运行! - peter70

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接