效果
MyAction.h
#pragma once
#pragma execution_character_set("utf-8") // utf-8
#include <QWidgetAction>
#include <QLabel>
#include <QLineEdit>
class MyAction : public QWidgetAction {
Q_OBJECT
public:
explicit MyAction(const QString &t = Q_NULLPTR, QWidget *parent = Q_NULLPTR);
~MyAction();
void setDatas(const QString &t);
protected:
QWidget* createWidget(QWidget *parent); // 创建界面
private:
QWidget *widget;
QLabel *label;
QLineEdit *lineEdit;
signals:
void dataChanged(const QString &t); // 发送数据修改
private slots:
void dataChanged();
};
MyAction.cpp
#pragma execution_character_set("utf-8") // utf-8
#include <QGridLayout>
#include "MyAction.h"
MyAction::MyAction(const QString &t/* = Q_NULLPTR*/, QWidget *parent/* = Q_NULLPTR*/)
: QWidgetAction(parent) {
widget = new QWidget(parent);
label = new QLabel(widget);
label->setText(t);
lineEdit = new QLineEdit(widget);
QGridLayout *layout = new QGridLayout(widget);
layout->setSpacing(1);
layout->setContentsMargins(1, 1, 1, 1);
layout->addWidget(label, 0, 0, 1, 1);
layout->addWidget(lineEdit, 0, 1, 1, 1);
layout->setColumnStretch(1, 1);
connect(lineEdit, &QLineEdit::returnPressed, this, [&]() {
dataChanged();
});
}
MyAction::~MyAction() {
}
void MyAction::setDatas(const QString &t) {
label->setText(t);
}
QWidget* MyAction::createWidget(QWidget *parent) {
widget->setParent(parent);
return widget;
}
void MyAction::dataChanged() {
QString text = lineEdit->text();
lineEdit->clear();
label->setText(text);
emit dataChanged(text);
}