将QGraphicsView添加到QBoxLayout

adding QGraphicsView to QBoxLayout

本文关键字:QBoxLayout 添加 QGraphicsView      更新时间:2023-10-16

我是QT新手,正在尝试使用应用程序。我刚刚用一些按钮编写了一个非常琐碎的应用程序。主要的想法是在我的应用程序中有一个小的"标志"。LAter我也想添加一些背景图像。

我从一个带有网格布局的示例应用程序中进行了编码,其中有一个QBoxLayout,用于对我的按钮进行分组。

正如你在我的代码中看到的,我已经尝试在各处添加徽标。当我在main.cpp中添加它时,我有两个视图,一个显示按钮,另一个显示我的徽标。我当然不想这样。所以我试着在mainwindow.cpp中添加它,但在这种情况下,我根本看不到我的徽标出现在任何地方:(

请告知。

这是代码:

main.cpp:

#include <QtGui/QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);  
    Window window;
    window.show();
/*
    QGraphicsScene scene;
    QGraphicsView view(&scene);
    QGraphicsPixmapItem item(QPixmap("/home/marc/Desktop/Niranjana/Images/logo.9.png"));
    scene.addItem(&item);
    view.show();
*/
    return a.exec();
}

主窗口.h

#ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
#include <QRadioButton>

class QGroupBox;
class Window : public QWidget
{
    Q_OBJECT
public:
    Window(QWidget *parent = 0);
    void onCheck_remote(int flag);
    void onCheck_local(int flag);

private:
    QRadioButton *button_local;
    QRadioButton *button_remote;
    QGroupBox *createPushButtonGroup();

};
#endif

主窗口.cpp

#include <QtGui>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include "mainwindow.h"
Window::Window(QWidget *parent)
    : QWidget(parent)
{
    QGridLayout *grid = new QGridLayout;
    QGraphicsScene scene;
    QGraphicsPixmapItem item(QPixmap("/home/test/logo.png"));
    QGraphicsView view(&scene);
    scene.addItem(&item);
    view.show();
    grid->addWidget(view.viewport(), 1, 1);

    grid->addWidget(createPushButtonGroup(), 2, 1);
    setLayout(grid);
    setWindowTitle(tr("My App"));
    resize(480, 420);
}
QGroupBox *Window::createPushButtonGroup()
{
    QGroupBox *groupBox = new QGroupBox();
  /*
    QGraphicsScene scene;
    QGraphicsPixmapItem item(QPixmap("/home/marc/Desktop/Niranjana/Images/logo.9.png"));
    QGraphicsView view(&scene);
    scene.addItem(&item);
    scene.setBackgroundBrush(Qt::white);
    view.show();
*/
    QPushButton *button1 = new QPushButton(tr("&Start"));
    QPushButton *button2 = new QPushButton(tr("&Stop"));
    button_local = new QRadioButton(tr("&with power"));
    button_remote = new QRadioButton(tr("without power"));
    button_local->setChecked(1);

    QVBoxLayout *vbox = new QVBoxLayout;
   // vbox->addSpacing(10);
   // vbox->addWidget(view.viewport());
    //vbox->addSpacing(10);
    vbox->addWidget(button1);
    vbox->addSpacing(10);
    vbox->addWidget(button2);
    vbox->addSpacing(50);
    vbox->addWidget(button_local);
    vbox->addWidget(button_remote);
    vbox->addStretch(1);
    groupBox->setLayout(vbox);

    return groupBox;
}

您应该

  • 使场景、视图和项目指针成为窗口类的成员
  • 在Window ctor中实例化它们
  • 执行grid->addWidget(view, 1, 1);

否则,在退出时,ctor中堆栈上实例化的所有项都将被删除。