调用setVisible(false)在QWidget的构造函数中将不起作用

时间:2019-03-31 10:26:03

标签: c++ qt

在QWidget的构造函数中调用this-> setvisible(false)时,它不一定会隐藏。在这里,我写了一个最小的示例,其中mw将隐藏而mw2不隐藏。

但是,以后仍然可以通过调用连接将mw2设置为隐藏。

为什么mw隐藏而不是mw2?

我想了解为什么添加此附件以及如何解决它。我在做错什么吗?


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

/*
 * ui_mainwindow.h is the default generated file for the mainwindow. I just added
 * a QVerticalLayout containing a QPushButton and a ScrollArea inside the central widget
 * (aka: verticalLayout, pushButton, scrollArea).
*/
#include "ui_mainwindow.h"


#include <QMainWindow>
#include <QTextBrowser>

class MyWidget: public QTextBrowser{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = nullptr)
        : QTextBrowser(parent)
    {
        this->setText("content");
        innerHide();
    }
    void innerHide(){
        this->hide();
    }
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

private:
    Ui::MainWindow *ui;
    MyWidget* mw2;
public:
    explicit MainWindow(QWidget *parent = nullptr):
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        MyWidget* mw = new MyWidget(this); // will hide
        mw2 = new MyWidget(this); // call for innerHide but won't hide
        ui->verticalLayout->addWidget(mw);
        ui->scrollArea->setWidget(mw2);

        connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(callHide())); // will hide when triggered
    }
    ~MainWindow(){
        delete ui;
    }
public slots:
    void callHide(){
        mw2->innerHide();
    }
};

#endif // MAINWINDOW_H


#include <QApplication>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

1 个答案:

答案 0 :(得分:1)

呼叫此行ui->scrollArea->setWidget(mw2);将使mw2再次可见。在构造函数的末尾调用MyWidget::innerHide

class Widget: public QWidget
{
public:
    Widget()
    {
        QScrollArea * area = new QScrollArea();
        QLabel* label = new QLabel("Should be hidden");
        QVBoxLayout* layout = new QVBoxLayout(this);
        layout->addWidget(area);

        label->hide(); // Hidden but will not work if before the next line
        area->setWidget(label); // Visible
        label->hide(); // Hidden
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Widget *w = new Widget();
    w->show();
    return app.exec();
}