Search code examples
c++qtqwidget

QWidget - Not sure where to start


I'm doing a college project in QT with C++. I basically have it all done, but I kind of want to end of a flourish! At the endgame, you get to the last room and press the control panel and a keypad appears (which is a .ui layout created as a QWidget) - the access code is a randomly generated 4 digit number in an earlier room.

Anyways, I want to pop up the QWidget with the keypad, get the user to press 4 buttons - each button would return a QString - and then press the confirm button. If it matches, game ends. If not, returned to room.

I just have no idea how to call the widget! The API haven't really help as I don't see anyway to assign a .ui form to the QWidget object.


Solution

  • The .ui file is a resource file. If the setup you have does not do this for you automatically, then you must use the uic tool to convert the .ui file to c++ source code.

     foo.ui -> ui_foo.h
    

    This header contains a class that creates the widgets and has members to acces each of the members once they have been created.

    class Ui_Foo {
       setupUi(QWidget *) { ...
       }
    }
    
    namespace Ui {
        class Foo: public Ui_Foo {};
    } // namespace Ui
    

    An instance of Ui::Foo is placed in your FooWidget

    // FooWidget.h
    //
    class FooWidget 
    : public QWidget {
        FooWidget(QWidget *);
        Ui::Foo  mUi;
    }
    

    and its setupUi is called in the constructor of your FooWidget

    // FooWidget.cpp
    // 
    FooWidget::FooWidget(QWidget *parent)
    : QWidget(parent)
    {
        mUi.setupUi(this);
    }