PDA

View Full Version : Create And Display QWidget in code



ShapeShiftme
16th May 2012, 09:36
Good day All.
Ive been using qt creator to do all my qt application development and therefore using ui pages in creator for design layout.
How ever i have the need to create a widget or dialog that i would like to do solely in code no ui page.

This is what i have done so far.

I created a new C++ class not qt class so it doesnt include the ui file.
the file is named "frm_maintenance_all"
I then included the file and open it so in my mainwindow.cpp



void MainWindow::openMaintenance()
{
frm_maintenance_all *newform = new frm_maintenance_all;

}


Then my header is



#ifndef FRM_MAINTENANCE_ALL_H
#define FRM_MAINTENANCE_ALL_H

#include <QWidget>
#include <QDialog>
#include <QtGui>
#include <QApplication>

class frm_maintenance_all : public QWidget
{
Q_OBJECT
public:
explicit frm_maintenance_all(QWidget *parent = 0);

signals:

public slots:

private slots:
void frm_create(QString tablename);

};

#endif // FRM_MAINTENANCE_ALL_H


and my cpp is



#include "frm_maintenance_all.h"

frm_maintenance_all::frm_maintenance_all(QWidget *parent) :
QWidget(parent)
{
frm_create("test");

}

void frm_maintenance_all::frm_create(QString tablename)
{


QWidget *frmnew = new QWidget;
QVBoxLayout *myhoz = new QVBoxLayout;

QLineEdit *myline = new QLineEdit;
QLineEdit *myline1 = new QLineEdit;

myhoz->addWidget(myline);
myhoz->addWidget(myline1);

//attempt here to add myhoz to frmnew via frmnew->addLayout does not work

frmnew->show();
frmnew->setWindowTitle("Maintenance Test");

}


you will see in the coment above i try to add the layout created to the frm however it does not give me the option to add widget or addlayout.
Is there something im doing wrong.

Or is there a better way to do this.

Regards

Charvi
16th May 2012, 10:03
Try using setLayout instead of addLayout.

ShapeShiftme
16th May 2012, 12:37
Thanks that worked Perfectly, such a stupid little thing.

Regards

amleto
16th May 2012, 19:59
what is the point in that class? why have it inherit from QWidget?

It will never be anything other than a blank window as it is. and the only thing it *does* do is make another widget and show it.

It would be more conventional to do this


#include "frm_maintenance_all.h"

frm_maintenance_all::frm_maintenance_all(QWidget *parent) :
QWidget(parent)
{
frm_create("test");

}

void frm_maintenance_all::frm_create(QString tablename)
{
QVBoxLayout *myhoz = new QVBoxLayout;

QLineEdit *myline = new QLineEdit;
QLineEdit *myline1 = new QLineEdit;

myhoz->addWidget(myline);
myhoz->addWidget(myline1);

//attempt here to add myhoz to frmnew via frmnew->addLayout does not work

setLayout(myhoz);
setWindowTitle("Maintenance Test");
show();
}

ShapeShiftme
19th May 2012, 07:04
Thanks that works great.