2014-01-08 75 views
5

我有一个Qt Quick项目,我只是添加了一些源文件。当试图建立我得到的错误信息:库需要QApplication。如何在Qt Quick项目中使用QApplication?

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. 
+0

你必须在创建任何QWidgets之前创建QApplication的实例。 – drescherjm

+0

@drescherjm:我可以在main()中同时使用QApplication和QGuiApplication循环吗? – Phat

+0

不是。我的意思是在任何QWidgets之前创建您的QGuiApplication实例。 – drescherjm

回答

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")); 
    ... 
} 

您可以找到以下职位的详细信息:

Introducing QWidget::createWindowContainer()

Combining Qt Widgets and QML with QWidget::createWindowContainer()

+0

谢谢,这看起来很有希望。我还没有测试过,但这正是我所期待的。我还阅读了您提供的其中一个链接,这在Android上无效。我没有在我的问题中指出这一点,但Android是我正在开发的平台之一。从我所读的内容来看,这是不可能的,因为在Android上,仅限于一个OpenGL表面(至少在Qt 5.1上,不知道它是否固定在Qt 5.2中)。如果您对如何解决问题有任何建议,请随时对此发表评论。我会试着去看看它是否有效(穿过手指和脚趾) – Phat