QT编辑器智能按钮

时间:2016-07-06 15:46:54

标签: c++ qt

我有一个带按钮的工具栏:撤消,重做,剪切,复制,粘贴,如下所示:

editmenu = menuBar()->addMenu(QObject::tr("&Edit"));
undoact = editmenu->addAction(QIcon(":images/undo.png"), QObject::tr("&Undo"));
QObject::connect(editwin, SIGNAL(undoAvailable(bool)), undoact, SLOT(setEnabled(bool)));
QObject::connect(undoact, SIGNAL(triggered()), editwin, SLOT(undo()));
undoact->setShortcuts(QKeySequence::keyBindings(QKeySequence::Undo));
undoact->setEnabled(false);
redoact = editmenu->addAction(QIcon(":images/redo.png"), QObject::tr("&Redo"));
QObject::connect(editwin, SIGNAL(redoAvailable(bool)), redoact, SLOT(setEnabled(bool)));
QObject::connect(redoact, SIGNAL(triggered()), editwin, SLOT(redo()));
redoact->setShortcuts(QKeySequence::keyBindings(QKeySequence::Redo));
redoact->setEnabled(false);
editmenu->addSeparator();
cutact = editmenu->addAction(QIcon(":images/cut.png"), QObject::tr("Cu&t"));
cutact->setShortcuts(QKeySequence::keyBindings(QKeySequence::Cut));
cutact->setEnabled(false);
copyact = editmenu->addAction(QIcon(":images/copy.png"), QObject::tr("&Copy"));
copyact->setShortcuts(QKeySequence::keyBindings(QKeySequence::Copy));
copyact->setEnabled(false);
pasteact = editmenu->addAction(QIcon(":images/paste.png"), QObject::tr("&Paste"));
pasteact->setShortcuts(QKeySequence::keyBindings(QKeySequence::Paste));

我想:

  1. 仅当剪贴板包含文本
  2. 时才会启用粘贴按钮
  3. 出于某种原因,我需要在限制的时间段内禁用所有按钮。在此之后我想启用所有按钮。但是当我启用时,每个按钮都会根据他的条件启用/禁用(例如,只有在有要撤消的内容时才启用撤销按钮,只有在有一些可以粘贴的文本时才会启用粘贴按钮... )
  4. 你建议我做什么?什么是最聪明/最简单的方法?

1 个答案:

答案 0 :(得分:2)

http://doc.qt.io/qt-5/qclipboard.html#signals

http://doc.qt.io/qt-5/qclipboard.html#details

创建从QClipboard对象到工具栏/ mainwindow类中的处理程序槽的连接。然后在处理程序槽中执行您想要发生在工具栏按钮上的逻辑。

例如:

http://doc.qt.io/qt-5/qclipboard.html#dataChanged

// in your constructor after creating your buttons:
QObject::connect(qApp->clipboard(), SIGNAL(dataChanged()), 
    this, SLOT(onClipboardDataChanged()));

// and then make another connection for the other relevant clipboard signal...
// selectionChanged()

然后在你的插槽中:

void MainWindow::onClipboardDataChanged()
{
     const QClipboard *clipboard = QApplication::clipboard();
     const QMimeData *mimeData = clipboard->mimeData();

     pasteact->setEnabled(mimeData->hasText());
     // or you could check the length of the text to see if it is non zero.
}

要立即禁用/重新设置所有按钮,请禁用父对象。

editToolbar->setEnabled(false);
//... after some period of time or transactions...
editToolbar->setEnabled(true);

但这可能不会禁用复制,剪切和粘贴的内置加速器。要杀死这些键盘快捷键,您可能需要在应用上添加事件过滤器。

http://doc.qt.io/qt-5/accelerators.html

http://doc.qt.io/qt-5/qobject.html#eventFilter

http://doc.qt.io/qt-5/qobject.html#installEventFilter

希望有所帮助。

PS。我还没有测试过这段代码。阅读文档。祝你好运。