Qt 5.3 QPlainTextEdit更改QTextCursor颜色

时间:2014-10-28 18:59:30

标签: c++ qt qt5

我想更改QPlainTextEdit小部件下的光标颜色。我能够将它的宽度设置为6,但我想改变它的颜色。有可能吗?

QFontMetrics fm(font());
setCursorWidth( fm.averageCharWidth() );
//setCursorColor is what I need.

感谢。

编辑:

包括图片以举例说明......

由此:

Initial Cursor Color

对此:

enter image description here

感谢。

Edit2:最终展望

enter image description here

2 个答案:

答案 0 :(得分:6)

您可以使用QTextCharFormat设置QPlainTextEdit中文字的颜色。使用QTextCharFormat::setForeground设置颜色。 然后使用样式表通过color属性更改光标的颜色。

QPlainTextEdit *p_textEdit = new QPlainTextEdit;
p_textEdit->setStyleSheet("QPlainTextEdit{color: #ffff00; background-color: #303030;"
                          " selection-background-color: #606060; selection-color: #ffffff;}");
QTextCharFormat fmt;
fmt.setForeground(QBrush(QColor(255,255,255)));
p_textEdit->mergeCurrentCharFormat(fmt);

答案 1 :(得分:4)

修改

您可以使用下一个样式表更改插入颜色:

ui->plainTextEdit->setStyleSheet(
            "QPlainTextEdit"
            "{"
            "color: yellow;"
            "}"
            );

但是还有另外一个问题,所有文字都变成了这种颜色。如何为文本设置新颜色但为插入符号留下旧颜色?我找到了这个解决方案,也许不是最好的:使用HTML代码:

ui->plainTextEdit->appendHtml("<font color = \"red\"> Sample Text</font>");

结果(如您想要插入符号和文本的原始颜色):

enter image description here

现在文字需要颜色,但插入符号有特殊颜色。这是解决方案,但对我来说有点脏,如果有人会找到更好的方法来改变文本的颜色而不改变插入颜色,请告诉它。

您只能更改小部件下的主光标:

QPixmap pix("pathToPixmap");
QCursor cur(pix);
ui->plainTextEdit->viewport()->setCursor(cur);

Qt有下一个嵌入游标:http://qt-project.org/doc/qt-5/qt.html#CursorShape-enum

Qt没有任何特定颜色的光标,所以你应该使用自己的pixmap。您可以使用带有简单箭头的图像,但使用其他颜色(如果它有alpha通道则更好)

网络上有许多不同的游标。