我不希望鼠标中键在我的QTextEdit中粘贴文本。 此代码不起作用。 TextEdit
inheritanceQTextEdit
。 鼠标中间button粘贴后,粘贴复制的文本。
void TextEdit::mousePressEvent ( QMouseEvent * e ) { if (e->button() == Qt::MidButton) { e->accept(); return; }; QTextEdit::mousePressEvent(e); }
由于鼠标点击通常是在释放按钮时注册的,您应该重新定义mouseReleaseEvent
函数。
您甚至不需要重新定义mousePressEvent
,因为中间按钮根本不由该函数处理。
我假设你在这里使用Linux; 在你处理鼠标事件之前,右键单击窗口很可能会触发MIME数据的插入,这就是为什么它仍在粘贴文本。
因此,根据Qt文档粘贴: – “修改QTextEdit可以粘贴什么以及如何粘贴,重新实现虚拟canInsertFromMimeData()和insertFromMimeData()函数。
我也遇到了同样的情况,就是说我的CustomQTextEdit
部分必须是不可编辑的 。
由于我真的很喜欢鼠标中键的粘贴功能,我不想禁用它。 所以,这里是(或多或少快速和肮脏的编码)我使用的解决方法:
void QTextEditHighlighter::mouseReleaseEvent(QMouseEvent *e) { QString prev_text; if (e->button() == Qt::MidButton) { // Backup the text as it is before middle button click prev_text = this->toPlainText(); // And let the paste operation occure... // e->accept(); // return; } // !!!! QTextEdit::mouseReleaseEvent(e); // !!!! if (e->button() == Qt::MidButton) { /* * Keep track of the editbale ranges (up to you). * My way is a single one range inbetween the unique * tags "//# BEGIN_EDIT" and "//# END_EDIT"... */ QRegExp begin_regexp = QRegExp("(^|\n)(\\s)*//# BEGIN_EDIT[^\n]*(?=\n|$)"); QRegExp end_regexp = QRegExp("(^|\n)(\\s)*//# END_EDIT[^\n]*(?=\n|$)"); QTextCursor from = QTextCursor(this->document()); from.movePosition(QTextCursor::Start); QTextCursor cursor_begin = this->document()->find(begin_regexp, from); QTextCursor cursor_end = this->document()->find(end_regexp, from); cursor_begin.movePosition(QTextCursor::EndOfBlock); cursor_end.movePosition(QTextCursor::StartOfBlock); int begin_pos = cursor_begin.position(); int end_pos = cursor_end.position(); if (!(cursor_begin.isNull() || cursor_end.isNull())) { // Deduce the insertion index by finding the position // of the first character that changed between previous // text and the current "after-paste" text int insert_pos; //, end_insert_pos; std::string s_cur = this->toPlainText().toStdString(); std::string s_prev = prev_text.toStdString(); int i_max = std::min(s_cur.length(), s_prev.length()); for (insert_pos=0; insert_pos < i_max; insert_pos++) { if (s_cur[insert_pos] != s_prev[insert_pos]) break; } // If the insertion point is not in my editable area: just restore the // text as it was before the paste occured if (insert_pos < begin_pos+1 || insert_pos > end_pos) { // Restore text (ghostly) ((MainWindow *)this->topLevelWidget())->disconnect(this, SIGNAL(textChanged()), ((MainWindow *)this->topLevelWidget()), SLOT(on_textEdit_CustomMacro_textChanged())); this->setText(prev_text); ((MainWindow *)this->topLevelWidget())->connect(this, SIGNAL(textChanged()), ((MainWindow *)this->topLevelWidget()), SLOT(on_textEdit_CustomMacro_textChanged())); } } } }