Home > Software design >  Qt Application with layout's, QPushButton and QGraphicsItem
Qt Application with layout's, QPushButton and QGraphicsItem

Time:03-01

I am trying to draw various shapes like rectangle, ellipse, text etc uisng QGraphicsView and QGraphicsScene. For that I am trying to create an interface where there will be a vertical layout and besides that there will be few buttons. On clicking those buttons, I can show various QGraphicsItem's on screen. I want to create this interface programatically but not using ui.
I tried and ended up this way.
enter image description here

I wanted buttons on the right side and verticalLayout on the left side and both should filled up the whole screen.
Here is my current implementation :

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    QGraphicsScene* scene = new QGraphicsScene(this);

    QGraphicsView* view = new QGraphicsView(this);
    view->setScene(scene);

    QWidget* mainWidget = new QWidget(this);
    QHBoxLayout *mainLayout = new QHBoxLayout();

    QVBoxLayout *buttonLayout = new QVBoxLayout();
    QVBoxLayout *vlayout2 = new QVBoxLayout();

    vlayout2->addWidget(view);

    QPushButton *btn1 = new QPushButton("Rectangle");
    btn1->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    
    QPushButton *btn2 = new QPushButton("Ellipse");
    btn2->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    
    QPushButton *btn3 = new QPushButton("Text");
    btn3->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );

    buttonLayout->addWidget(btn1);
    buttonLayout->addWidget(btn2);
    buttonLayout->addWidget(btn3);
    buttonLayout->addStretch();

    mainLayout->addLayout(buttonLayout);
    mainLayout->addLayout(vlayout2);

    mainWidget->setLayout(mainLayout);
}    

Can anyone guide me ?

CodePudding user response:

Actually, it should work with the hints given in my comments.

I made an MCVE to convince myself:

#include <QtWidgets>

int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QWidget qMain;
  qMain.setWindowTitle("Test Box Layout");
  qMain.resize(640, 320);
  QHBoxLayout qHBox;
  QVBoxLayout qVBoxBtns;
  QPushButton qBtnRect("Rectangle");
  qVBoxBtns.addWidget(&qBtnRect);
  QPushButton qBtnCirc("Circle");
  qVBoxBtns.addWidget(&qBtnCirc);
  QPushButton qBtnText("Text");
  qVBoxBtns.addWidget(&qBtnText);
  qVBoxBtns.addStretch();
  qHBox.addLayout(&qVBoxBtns);
  QVBoxLayout qVBoxView;
  QGraphicsView qView;
  qVBoxView.addWidget(&qView, 1);
  qHBox.addLayout(&qVBoxView, 1);
  qMain.setLayout(&qHBox);
  qMain.show();
  // runtime loop
  return app.exec();
}

Output: Snapshot of testQBoxLayout (GIF Animation)

Thus, there must be something else in OP's code…

Unfortunately, OP didn't expose an Snapshot of (now broken) testQBoxLayout (GIF Animation)

  • Related