c++ - 如何访问子类中的小部件?

标签 c++ qt

我已经创建了 QLineEdit 的子类,并且我在小部件的右侧添加了一个按钮,因此我可以进行一体化路径浏览控制。但是,我需要从 resizeEvent 中访问按钮,这样我才能将按钮正确地放置在行编辑的右侧。我收到错误,我假设这是由于我创建按钮的方式所致。

enter image description here

lineeditpath.h

#ifndef LINEEDITPATH_H
#define LINEEDITPATH_H

#include <QLineEdit>
#include <QFileDialog>
#include <QPushButton>

class LineEditPath : public QLineEdit
{
    Q_OBJECT
public:
    explicit LineEditPath(QWidget *parent = 0);

signals:

public slots:

protected:
    void resizeEvent(QResizeEvent *event) override;

private:
    QFileDialog *dialog;
    QPushButton *button;
};

#endif // LINEEDITPATH_H

lineedithpath.cpp

#include "lineeditpath.h"
#include <QLineEdit>
#include <QPushButton>

LineEditPath::LineEditPath(QWidget *parent) : QLineEdit(parent) {
    setAcceptDrops(true);

    auto button = new QPushButton("...", this);
    button->setFixedWidth(30);
    button->setCursor(Qt::CursorShape::PointingHandCursor);
    button->setFocusPolicy(Qt::FocusPolicy::NoFocus);
    setTextMargins(0,0,30,0); }

void LineEditPath::resizeEvent(QResizeEvent *event) {
    QLineEdit::resizeEvent(event);

    // Resize the button: ERROR
    button->move(width()-button->sizeHint().width(), 0);

}

错误:

---------------------------
Signal Received
---------------------------
<p>The inferior stopped because it received a signal from the operating system.<p><table><tr><td>Signal name : </td><td>SIGSEGV</td></tr><tr><td>Signal meaning : </td><td>Segmentation fault</td></tr></table>
---------------------------
OK   
---------------------------

最佳答案

auto button = new QPushButton("...", this); 在您的构造函数中 初始化 button 的成员变量你的类。它创建一个具有相同名称的新局部变量,该变量隐藏成员变量并在构造函数主体的末尾超出范围。您的成员变量永远不会被初始化。

你想要 button = new QPushButton("...", this); - 甚至更好;将其移至您的构造函数初始化列表,而不是使用 ctor 主体。

使用初始化列表:

LineEditPath::LineEditPath(QWidget *parent) :
    QLineEdit(parent), 
    button(new QPushButton("...", this)) 
{

您也永远不会初始化您的 dialog 成员变量。

关于c++ - 如何访问子类中的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52338463/

相关文章:

c# - 将此行从 C++ 转换为 C#

c++ - 使用蛮力求解方程

c++ - 在 Debug模式下构建 Qt 5.10 时 MSVC 编译器崩溃

c++ - 使用 C++ 和 Windows API 以编程方式更改墙纸

c++ - 从 QListWidget 中的小部件获取变量

c++ - Qt 项目中的前向声明

c++ - _GLIBCXX_VISIBILITY 是什么?

c++ - 根据特殊条件定义函数类型

c++ - 在 move 构造函数之前调用析构函数?

c++ - Qt如何实现一个进程循环?