在Qt/C++中实现撤销功能(如Ctrl + Z),可以通过以下步骤来实现:
class MyUndoCommand : public QUndoCommand {
public:
MyUndoCommand(QObject *receiver, const QString &methodName, const QVariant &value);
void undo() override;
void redo() override;
private:
QObject *m_receiver;
QString m_methodName;
QVariant m_value;
};
class MyWidget : public QWidget {
Q_OBJECT
public:
MyWidget(QWidget *parent = nullptr);
private:
QLineEdit *m_lineEdit;
QUndoStack *m_undoStack;
public slots:
void setText(const QString &text);
};
MyWidget::MyWidget(QWidget *parent) : QWidget(parent) {
m_lineEdit = new QLineEdit(this);
m_undoStack = new QUndoStack(this);
connect(m_lineEdit, &QLineEdit::textChanged, this, &MyWidget::setText);
}
void MyWidget::setText(const QString &text) {
MyUndoCommand *command = new MyUndoCommand(m_lineEdit, "setText", text);
m_undoStack->push(command);
}
MyUndoCommand::MyUndoCommand(QObject *receiver, const QString &methodName, const QVariant &value)
: m_receiver(receiver), m_methodName(methodName), m_value(value) {
}
void MyUndoCommand::undo() {
QMetaObject::invokeMethod(m_receiver, m_methodName.toStdString().c_str(), Qt::DirectConnection, Q_ARG(QVariant, m_value));
}
void MyUndoCommand::redo() {
QMetaObject::invokeMethod(m_receiver, m_methodName.toStdString().c_str(), Qt::DirectConnection, Q_ARG(QVariant, m_value));
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
private:
MyWidget *m_myWidget;
protected:
void keyPressEvent(QKeyEvent *event) override;
};
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
m_myWidget = new MyWidget(this);
setCentralWidget(m_myWidget);
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Z && event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ShiftModifier) {
m_myWidget->m_undoStack->redo();
} else {
m_myWidget->m_undoStack->undo();
}
} else {
QMainWindow::keyPressEvent(event);
}
}
这样,就可以在Qt/C++中实现撤销功能了。
领取专属 10元无门槛券
手把手带您无忧上云