开发者

Handling multiple ui files in Qt

开发者 https://www.devze.com 2023-03-24 02:42 出处:网络
I am new to the Qt framework and am trying to load another UI file when SubmitClicked. The file\'s name is Form.ui

I am new to the Qt framework and am trying to load another UI file when SubmitClicked. The file's name is Form.ui

//MainWindow.cpp
#include 开发者_如何转开发"mainwindow.h"
#include "ui_mainwindow.h"
#include "form.h"
#include <QtCore/QCoreApplication>

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

}

MainWindow::~MainWindow()
{
   delete ui;
}
void MainWindow:: SubmitClicked()
{
   Form* f= new Form(this);
   f->show();
   f->raise();
   f->activateWindow();
}




//Form.cpp
#include "form.h"
#include "ui_form.h"

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

Form::~Form()
{
delete ui;
}

This didn't work out! Can you tell me what's wrong?


The .ui file is simply where the code for GUI elements gets stored. This code is generated by the QtDesigner in most cases. It's similar to Visual Studio's .rc file and wizard generated GUI in function and form. This file will either be loaded at compile time which is the default or at runtime via the QUiLoader. If you want dynamically generated UI at runtime the latter is the option you need to look into starting with QtUiTools

On a side note the class Form does not exist in Qt so this is either a class you made or a typo. If you simply want to declare and show a window or dialog then derive from the appropriate base class and call show() or the appropriate method.

For example something simple like this where MainWindow is your own user defined class derived from QMainWindow:

#include <QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(application);
    QApplication app(argc, argv);
    MainWindow mainWin;
    mainWin.show();
    return app.exec();
}

Edit:

Ah so Form is a QWidget class. Are you missing the Q_OBJECT macro in your Form class? You also generally only call setupUi once for the main window of the application to load your resources and such where as user defined subclasses it's often easier to define gui objects for the class programmatically.

//Form.h
class Form : public QWidget
{
    Q_OBJECT // this is needed for the MOC aka qmake
public:
    Form(QWidget *parent);
    virtual ~Form();
private:
    QTextEdit m_text;
};

//Form.cpp
#include "form.h"

Form::Form(QWidget *parent) : QWidget(parent)
{
    setCentralWidget(&m_text);
}

Form::~Form()
{
}

It sounds almost like you're confusing your class object with your ui namespace files.

0

精彩评论

暂无评论...
验证码 换一张
取 消