代码之家  ›  专栏  ›  技术社区  ›  Kyrill

在主窗口中打开QGraphicScene子窗口小部件

  •  1
  • Kyrill  · 技术社区  · 11 年前

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

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

    当我在子窗口小部件中创建一个标签时,它会在主窗口中正确显示。所以问题似乎出在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();
    }
    

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

    1 回复  |  直到 11 年前
        1
  •  1
  •   thuga    11 年前

    您正在创建一个新的 QGraphicsScene QGraphicsView 每次你设置图片时。你没有把你的 view 在任何布局中,或为其设置父级,因此当您调用时,它将在新窗口中打开 view->show() .

    您应该创建 Q图形视图 和一个 Q图形场景 在构造函数中。

    //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));
    }