【问题标题】:open a QGraphicScene child widget in the mainwindow在主窗口中打开一个 QGraphicScene 子窗口小部件
【发布时间】:2013-10-07 14:44:35
【问题描述】:

我正在尝试在 MainWindow 中创建一个 QGraphicScene(具有适当的视图)。 场景在单独的类中定义(主窗口的子小部件)。

打开动作效果很好,我可以打开每张图片,但它们总是以新的方式打开 窗口而不是在 MainWindow 中。

当我在子小部件中创建一个标签(左右)时,它会在主窗口中正确显示。所以问题似乎是 QGraphicScene 或 QGraphicView。

主窗口:

MainWindow::MainWindow()
{
    QWidget *widget = new QWidget;
    setCentralWidget(widget);

    PictureArea = new picturearea(this);

    QHBoxLayout *HLayout = new QHBoxLayout(this); 

    HLayout->addWidget(PictureArea,1);   

    widget->setLayout(HLayout); 

    createActions();                          
    createMenus();                

    this->setMinimumSize(800,600);
    this->resize(800,600);


}

...

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"),  
    QDir::currentPath(), tr("Image Files (*.png *.jpg)"));

    if (!fileName.isEmpty())
    {
        QImage image(fileName);
        if (image.isNull())
        {
            QMessageBox::information(this, tr("Image Viewer"), 
            tr("Cannot load %1.").arg(fileName));
            return;
        }
        //transfer to child widget, guess no mistakes so far
        PictureArea->setPicture(image);       
    }


}

图片区域:

picturearea::picturearea(QWidget *parent) : QWidget(parent)
{



}

void picturearea::setPicture(QImage image)
{   
    QGraphicsScene* scene = new QGraphicsScene();
    QGraphicsView* view = new QGraphicsView(scene);

    QGraphicsPixmapItem* item = 
                new QGraphicsPixmapItem(QPixmap::fromImage(image));
    scene->addItem(item);

    view->show();
}

如何在 MainWindow 中而不是在单独的窗口中创建场景?我使用的是 QT 4.7.4,Windows7 64bit。

【问题讨论】:

    标签: qt qgraphicsview qgraphicsitem qgraphicsscene


    【解决方案1】:

    每次设置图片时,您都会创建一个新的QGraphicsSceneQGraphicsView。而且您不会将 view 放在任何布局中或为其设置父级,因此当您调用 view->show() 时它会在新窗口中打开。

    您应该在构造函数中创建QGraphicsViewQGraphicsScene

    //picturearea.h
    ...
    public:
        QGraphicsView *view;
        QGraphicsScene *scene;        
    ...
    

     

    //pircurearea.cpp
    picturearea::picturearea(QWidget *parent) : QWidget(parent)
    {
        this->setLayout(new QVBoxLayout);
        view = new QGraphicsView(this);
        this->layout()->addWidget(view);
        scene = new QGraphicsScene;
        view->setScene(scene);
    }
    
    void picturearea::setPicture(QImage image)
    {
        scene->clear();
        scene->addPixmap(QPixmap::fromImage(image));
    }
    

    【讨论】:

    • 它有效 :) 非常感谢。这正是我想要的。伙计……当然,布局。我太傻了^^
    猜你喜欢
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多