如何在构造函数外部访问小部件的内容?

时间:2019-04-15 16:58:00

标签: qt widget

在使用功能ShowMessage()单击QPushButton之后,我想显示我在QLineEdit小部件中编写的内容。如何在构造函数之外访问该内容?

尝试将创建的QLineEdit对象放入私有变量。

我的CPP文件

#include "manualwidget.h"
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QMessageBox>

ManualWidget::ManualWidget(QWidget *parent) : QWidget(parent)
{
    QLabel *label = new QLabel(this);
    QLineEdit *lineEdit = new QLineEdit(this);
    QPushButton *pushButton = new QPushButton(this);
    QHBoxLayout *layout = new QHBoxLayout();

    label->setText("Enter text:");
    pushButton->setText("Ok");
    layout->addWidget(label);
    layout->addWidget(lineEdit);
    layout->addWidget(pushButton);

    setLayout(layout);

    connect(pushButton,SIGNAL(clicked()),this ,SLOT(showMessage()));
    connect(lineEdit, SIGNAL(returnPressed()),this, SLOT(showMessage()));


}

void ManualWidget::showMessage(){

    QMessageBox::information(this, "Message", "The text entered in the "
     "manual widget window is:\n" + m_lineEdit->text());

}

我的头文件

#ifndef MANUALWIDGET_H
#define MANUALWIDGET_H

#include <QWidget>
#include <QLineEdit>

class ManualWidget : public QWidget
{
    Q_OBJECT
public:
    explicit ManualWidget(QWidget *parent = nullptr);

signals:


public slots:

private slots:
    void showMessage();
private:
    QLineEdit m_lineEdit;
};

#endif // MANUALWIDGET_H

1 个答案:

答案 0 :(得分:0)

@eyllanesc建议可能有用,但不应作为首选方法。 Qt有自己的内存模型,应该优先使用它。因此,“ QLineEdit m_lineEdit”应更改为例如“ QLineEdit * m_lineEdit”,在构造函数中,您应该通过以下方式对其进行初始化:

// Instance of the QLineEdit will be owned by the ManualWidget which is part of Qt memory management now.
m_lineEdit = new QLineEdit(this);

然后,以下行:

layout->addWidget(lineEdit);

可以更改为:

layout->addWidget(m_lineEdit);

为什么使用“ QLineEdit m_lineEdit”不好?因为Qt可能出于某种原因想要销毁该对象(您仍然可以调用m_lineEdit.deleteLater()),并且您可能最终陷入“双重销毁”情况,这将导致应用程序崩溃。您可以说,通过这种方式,冲突的内存模型将相互作用。

相关问题