自定义QAction

效果

test_action

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);
}

本文作者:vanxkr

本文链接:http://www.vanxkr.com/2020/10/my-action

版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0许可协议。转载请注明出处!

Qt QAxObject 批量写入 Excel
0 条评论
已登录,注销 取消