728x90

Combobox에 따라 Layout에 있는 Label을 바꾸려고 합니다. Combobox에 index가 바뀌면 replaceWidget 함수를 호출하도록 작성했습니다.

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

    QLabel* pLabel = new QLabel("test1");
    QLabel* pLabel2 = new QLabel("test2");

    labelList.append(pLabel);
    labelList.append(pLabel2);

    ui->comboBox->addItem(pLabel->text(), 0);
    ui->comboBox->addItem(pLabel2->text(),1);

    ui->verticalLayout->addWidget(pLabel);
    pCurrent = pLabel;
    connect(ui->comboBox, &QComboBox::currentIndexChanged, [&] (int index) {
        auto label = labelList.value(index);
        ui->verticalLayout->replaceWidget(pCurrent, label);
        pCurrent = label;
    });
}

그런데 실제로 Replace 해보면 이전의 Widget이 남아 있습니다.

이럴 경우에는 2가지 해결 방법이 있습니다. 이전의 widget을 delete 시키는 방법과 기존 parent를 없애는 방법입니다.

하지만 delete를 하는 방식의 큰 문제는 위와 같이 교체된 widget도 나중에 사용해야 하는 경우에는 맞지 않습니다. 이럴 때는 교체된 widget의 Parent를 0으로 넘겨주면 됩니다.

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

    QLabel* pLabel = new QLabel("test1");
    QLabel* pLabel2 = new QLabel("test2");

    labelList.append(pLabel);
    labelList.append(pLabel2);

    ui->comboBox->addItem(pLabel->text(), 0);
    ui->comboBox->addItem(pLabel2->text(),1);

    ui->verticalLayout->addWidget(pLabel);
    pCurrent = pLabel;
    connect(ui->comboBox, &QComboBox::currentIndexChanged, [&] (int index) {
        auto label = labelList.value(index);
        ui->verticalLayout->replaceWidget(pCurrent, label);
        pCurrent->setParent(0);
        pCurrent = label;
    });
}

728x90

+ Recent posts