2016-07-06 115 views
1

我有按鈕的工具欄:撤銷,重做,剪切,複製,粘貼,象下面這樣: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. 出於某種原因,我需要禁用所有按鈕一段時間。在此之後,我想啓用所有按鈕。但是,當我啓用時,根據自己的情況啓用/禁用每個按鈕(例如,撤消按鈕僅在需要撤消的情況下才能啓用,只有在存在可以粘貼的文本時才啓用粘貼按鈕... )

你建議我做什麼?什麼是最聰明/最簡單的方法?

回答

2

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

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

在工具欄/ MainWindow類創建一個從QClipboard對象到一個處理槽連接。然後在處理程序插槽中執行您希望發生在您的工具欄按鈕上的邏輯。

例如:

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. 
} 

要禁用/ renable一次所有的按鈕,禁用父對象來代替。

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。我沒有測試過這段代碼。閱讀文檔。祝你好運。