Qtextedit边沿触发 用C++
时间: 2023-09-07 20:14:19 浏览: 148
如果您使用的是C++编写的Qt程序,可以使用类似的方法来检测QTextEdit的边沿触发事件。以下是一个示例:
```c++
#include <QTextEdit>
#include <QApplication>
#include <QEvent>
#include <QTextCursor>
#include <QPoint>
class MyTextEdit : public QTextEdit {
public:
MyTextEdit(QWidget *parent = nullptr) : QTextEdit(parent) {
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setLineWrapMode(QTextEdit::NoWrap);
}
bool event(QEvent *event) override {
if (event->type() == QEvent::MouseMove) {
QTextCursor cursor = cursorForPosition(static_cast<QMouseEvent *>(event)->pos());
if (cursor.atStart() || cursor.atEnd()) {
QApplication::setOverrideCursor(Qt::ArrowCursor);
return true;
}
}
return QTextEdit::event(event);
}
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
QTextCursor cursor = cursorForPosition(event->pos());
if (cursor.atStart()) {
setTextCursor(cursor);
QApplication::setOverrideCursor(Qt::SizeHorCursor);
m_drag_start_x = event->pos().x();
return;
} else if (cursor.atEnd()) {
setTextCursor(cursor);
QApplication::setOverrideCursor(Qt::SizeHorCursor);
m_drag_start_x = event->pos().x();
return;
}
}
QTextEdit::mousePressEvent(event);
}
void mouseMoveEvent(QMouseEvent *event) override {
if (event->buttons() & Qt::LeftButton) {
int diff = event->pos().x() - m_drag_start_x;
QTextCursor cursor = textCursor();
if (cursor.atStart()) {
if (diff < 0) {
return;
}
cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
} else if (cursor.atEnd()) {
if (diff > 0) {
return;
}
cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
} else {
return;
}
setTextCursor(cursor);
m_drag_start_x = event->pos().x();
} else {
QTextEdit::mouseMoveEvent(event);
}
}
void mouseReleaseEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
QApplication::restoreOverrideCursor();
}
QTextEdit::mouseReleaseEvent(event);
}
private:
int m_drag_start_x = 0;
};
```
这段代码会在鼠标移动到文本编辑器的边缘时显示一个箭头光标,并且在鼠标按下并拖动边缘时,会使文本编辑器的宽度相应地增加或减少。
阅读全文