我想创建一个按钮,当用户右键单击按钮时,会出现一个上下文菜单,让用户可以选择替换按钮上的文本。当用户选择替换选项时,他们可以编辑按钮本身的文本标签。
我已经右键单击以创建上下文菜单,我可以拦截关键事件来更改标签,但是当我这样做时,我必须处理所有各种键盘功能,就像删除一样,为自己。
我想知道是否有更好的方法来做到这一点。有没有办法可以在按钮上放置QLineEdit来编辑按钮文本?
这是我开始使用的代码。
EventButton::EventButton(QWidget *parent) :
QPushButton(parent)
{ }
void EventButton::mousePressEvent(QMouseEvent *e) {
if (e->button() == Qt::RightButton) {
QMenu contextMenu;
contextMenu.addAction("Replace Text", this, [=] {
this->grabKeyboard();
this->setText("");
});
QPoint globalPos = mapToGlobal(e->pos());
contextMenu.exec(globalPos);
} else {
emit clicked();
}
}
void EventButton::keyPressEvent(QKeyEvent *e) {
// Check for return key
if ((e->key() == Qt::Key_Enter) || (e->key() == Qt::Key_Return)) {
this->releaseKeyboard();
emit buttonTitleChanged(this->text());
} else {
QString text = this->text();
text.append(e->key());
this->setText(text);
}
}
答案 0 :(得分:0)
您只需在按钮中添加QLineEdit
个孩子即可。我还会给按钮一个网格布局,以自动处理行编辑定位和调整大小并覆盖contextMenuEvent
以显示菜单,最终得到如下内容:
#include <QPushButton>
#include <QMenu>
#include <QAction>
#include <QContextMenuEvent>
#include <QGridLayout>
class EventButton : public QPushButton
{
Q_OBJECT
QLineEdit * lineEdit;
public:
explicit EventButton(const QString &text, QWidget *parent) :
QPushButton(text, parent)
{
lineEdit = new QLineEdit();
lineEdit->setAlignment(Qt::AlignCenter | Qt::AlignHCenter);
lineEdit->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
connect(lineEdit, &QLineEdit::editingFinished, [=](){
setText(lineEdit->text());
lineEdit->hide();
});
QGridLayout * gridlayout = new QGridLayout();
gridlayout->setMargin(0);
setLayout(gridlayout);
gridlayout->addWidget(lineEdit);
lineEdit->hide();
}
protected:
void contextMenuEvent(QContextMenuEvent *event) override
{
QMenu contextMenu;
contextMenu.addAction("Replace Text", this, [=] {
QString text = this->text();
lineEdit->setText(text);
lineEdit->setSelection(0, text.size());
lineEdit->show();
lineEdit->setFocus();
});
QPoint globalPos = mapToGlobal(event->pos());
contextMenu.exec(globalPos);
}
};