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