在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();
}

最佳答案

呼叫此行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();
}

10-08 16:26