简体   繁体   中英

Adding custom QWidget during runtime

I'm trying to implement a custom widget hierarchy: QMainWindow -> QFrame -> MyWidget -> QFrame -> MySubWidget

Here is how MyWidget class looks like:

    class MyWidget : public QWidget {
        Q_OBJECT
    public:
        MyWidget(QWidget *parent = 0, ...);
        ...
    public slots:
        void SlotFunction(int i);
        ...
    private:
        MySubWidget *sub_w;
        QFrame *sub_frame;
        ...
    }

If I try to create an MySubWidget during MyWidget constructor, then all MySubWidget elements are shown as intended:

    MyWidget::MyWidget (...) : QWidget(parent) {
        ...
        sub_frame = new QFrame(this);
        ...
        sub_w = new MySubWidget(sub_frame); // commented out on a runtime test
    }

But if I try to add subwidget during runtime, sub_frame remains blank. Ie signal reaction:

    void MyWidget::SlotFunction(int i) {
        sub_w = new MySubWidget(sub_frame); // update, repaint, show and hide methods aren't helphul
    }

I know this is an old question, but I was having a very similar issue and it turned out to be a lack of call to the QWidget::show(). Perhaps that was your problem as well?

My question here: Dynamically add instance inherited from QWidget

Cheers.

Are you reaching your function?

At the top of your function before making a new instance of MySubWidget put:

qDebug() << Q_FUNC_INFO;

Is the slot connected properly?

Qt will let you know if it is unable to connect a slot using a runtime warning. Look at the debug output that shows up in Qt Creator and it may mention a reason why the slot was never reached.

Is subframe visible?

If the parent of your object isn't visible, then showing or hiding the child object will only affect it when the parent is shown.

Hope that helps. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM