Qt 5.8 QTextEdit文本光标颜色不会改变

时间:2019-04-27 06:06:57

标签: qt colors caret qtextedit

我试图将文本光标放在QTextEdit红色(rgb(255,0,0))上。尽管尽我最大的努力,它仍然闪烁白色。

从我发现的内容来看,样式表的“颜色”属性应该更改光标的颜色。不知道怎么了。

我的代码:

    textEntry = new QTextEdit();
    textEntry->setFont(QFont("Electrolize", 9, 1));
    textEntry->setMinimumHeight(25);
    textEntry->setMaximumHeight(25);
    textEntry->setLineWrapMode(QTextEdit::NoWrap);
    textEntry->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    textEntry->setStyleSheet("color: rgb(255, 0, 0);"
                             "border: 1px solid rgb(255, 0, 0);");

编辑: 我鼓励完整阅读Scheff的答案。这很棒。我注意到,用他的解决方案创建的光标没有闪烁,所以我想与(没有经验的)其他人共享从Scheff的代码派生的闪烁版本。

TextEdit.h

#ifndef TEXTEDIT_H
#define TEXTEDIT_H

#include <QTextEdit>
#include <QTimer>

class TextEdit : public TextEdit
{
    Q_OBJECT
public:
    explicit TextEdit(QWidget *parent = nullptr);

private:
    QTimer *timer;
    QPainter *pPainter;
    bool bCursorVisible;

protected:
    virtual void paintEvent(QPaintEvent *pEvent) override;

signals:
    sendUpdate();

public slots:
    void timerSlot();
};

#endif // TEXTEDIT_H

TextEdit.cpp

#include "textedit.h"

#include <QPainter>
#include <QColor>
#include <QTimer>

TextEdit::TextEdit(QWidget *parent) : QTextEdit(parent) {
    bCursorVisible = true;

    timer = new QTimer(this);
    timer->start(500);
    connect(this, SIGNAL(sendUpdate()), this, SLOT(update()));
    connect(timer, SIGNAL(timeout()), this, SLOT(timerSlot()));
}

void TextEdit::paintEvent(QPaintEvent *event)
{
  // use paintEvent() of base class to do the main work
  QTextEdit::paintEvent(event);
  // draw cursor (if widget has focus)
  if (hasFocus()) {
    if(bCursorVisible) {
        const QRect qRect = cursorRect(textCursor());
        QPainter qPainter(viewport());
        qPainter.fillRect(qRect, QColor(255, 0, 0, 255));
    } else {
        const QRect qRect = cursorRect(textCursor());
        QPainter qPainter(viewport());
        qPainter.fillRect(qRect, QColor(0, 0, 0, 255));
    }
  }
}

void TextEdit::timerSlot() {
    if(bCursorVisible) {
        bCursorVisible = false;
    } else {
        bCursorVisible = true;
    }

    emit sendUpdate();
}

2 个答案:

答案 0 :(得分:2)

事先与OP进行过交谈,因为我非常怀疑QTextEdit的颜色属性是否也与文本光标的颜色有关。

我在Qt Style Sheets Reference中找到的所有内容:

  

用于呈现文本的颜色。

     

所有尊重QWidget :: palette的小部件都支持此属性。

     

如果未设置此属性,则默认值为在窗口小部件的面板中为QWidget :: foregroundRole(通常为黑色)设置的任何值。

出于好奇,我摆弄了QTextEdit的颜色。

  1. 我可以复制OP中描述的内容:
    更改QTextEdit的文本颜色(例如,使用QTextEdit::setTextColor())会影响随后键入的插入文本,但不会改变文本光标的颜色(至少在我测试的平台上)。 / p>

  2. 在摆弄的同时我意识到了另一个鼓励我写这个答案的事实:
    恕我直言,文本光标会忽略任何颜色设置。相反,它会反转绘制的文本光标栏下方的像素。
    看看QPainter::RasterOp_NotSource,了解我的意思。

我的示例应用程序testQTextEditCursorColor.cc

#include <QtWidgets>

class ColorButton: public QPushButton {
  private:
    QColor _qColor;

  public:
    explicit ColorButton(
      const QString &text, const QColor &qColor = Qt::black,
      QWidget *pQParent = nullptr):
      QPushButton(text, pQParent)
    {
      setColor(qColor);
    }
    virtual ~ColorButton() = default;
    ColorButton(const ColorButton&) = delete;
    ColorButton& operator=(const ColorButton&) = delete;

    const QColor& color() const { return _qColor; }
    void setColor(const QColor &qColor)
    {
      _qColor = qColor;
      QFontMetrics qFontMetrics(font());
      const int h = qFontMetrics.height();
      QPixmap qPixmap(h, h);
      qPixmap.fill(_qColor);
      setIcon(qPixmap);
    }

    QColor chooseColor()
    {
      setColor(QColorDialog::getColor(_qColor, this, text()));
      return _qColor;
    }
};

int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  qDebug() << app.style();
  // setup GUI
  QMainWindow qWin;
  qWin.resize(250, 100);
  qWin.setWindowTitle("Test Set Cursor Color");
  QTextEdit qTextEdit;
  qWin.setCentralWidget(&qTextEdit);
  QToolBar qToolBar;
  ColorButton qBtnColor("Text Color", qTextEdit.palette().color(QPalette::Text));
  qToolBar.addWidget(&qBtnColor);
  ColorButton qBtnColorBg("Background", qTextEdit.palette().color(QPalette::Base));
  qToolBar.addWidget(&qBtnColorBg);
  qWin.addToolBar(&qToolBar);
  qWin.show();
  // install signal handlers
  QObject::connect(&qBtnColor, &QPushButton::clicked,
    [&]() { qTextEdit.setTextColor(qBtnColor.chooseColor()); });
  QObject::connect(&qBtnColorBg, &QPushButton::clicked,
    [&]() {
      QPalette qPal = qTextEdit.palette();
      qPal.setColor(QPalette::Base, qBtnColorBg.chooseColor());
      qTextEdit.setPalette(qPal);
    });
  // runtime loop
  return app.exec();
}

和相应的Qt项目文件testQTextEditCursorColor.pro

SOURCES = testQTextEditCursorColor.cc

QT += widgets

已在Windows 10的cygwin64中进行了编译和测试:

$ qmake-qt5 testQTextEditCursorColor.pro

$ make && ./testQTextEditCursorColor
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQTextEditCursorColor.o testQTextEditCursorColor.cc
g++  -o testQTextEditCursorColor.exe testQTextEditCursorColor.o   -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread 
Qt Version: 5.9.4
QFusionStyle(0x6000e10c0, name = "fusion")

Snapshot in X11 (white background) Snapshot in X11 (black background)

因此,黑色代表白色光标,白色代表黑色光标(与任何颜色设置无关)。假设我的上述说法正确,青色背景(#00ffff)应该使红色光标(#ff0000):

Snapshot in X11 (cyan background)

为了进行比较,我编写了一个CMake脚本CMakeLists.txt

project(QTextEditCursorColor)

cmake_minimum_required(VERSION 3.10.0)

set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(Qt5Widgets CONFIG REQUIRED)

include_directories("${CMAKE_SOURCE_DIR}")

add_executable(testQTextEditCursorColor testQTextEditCursorColor.cc)

target_link_libraries(testQTextEditCursorColor Qt5::Widgets)

并再次在VS2017中进行编译和测试:

Qt Version: 5.11.2
QWindowsVistaStyle(0x1c1ed936690, name = "windowsvista")

(请注意,不同样式的引擎。)

Snapshot in Windows 10 (white background) Snapshot in Windows 10 (black background)

Windows GDI中的渲染使字形像素也明显反转(但是我在上面的X11测试中注意到了相同的意思):

Cursor in Windows 10 (5× magnified)


请记住以上几点,显而易见的是,使用中间灰色作为背景色是个坏主意。例如按位的非#808080#7f7f7f,这两种颜色之间几乎没有对比度。 (我没有提供快照,因为我无法识别正确的时间来敲击 Print 键以绘制带有文本光标的快照。)


OP引用了另一个常见问题解答:SO: Qt 5.3 QPlainTextEdit Change the QTextCursor color。尽管此答案已被接受并被接受,但是如上所述,以任何其他方式改变我这边的光标颜色都无济于事。这些是我在示例中尝试过的修改:

  • QTextEdit代替QPlainTextEdit
  • 使用qTextEdit.setCursorWidth()更改文本光标的宽度
  • 使用样式表,而不是修改调色板中的颜色

包括在链接的答案“字面上”中使用公开的代码。


与thuga(SO: Qt 5.3 QPlainTextEdit Change the QTextCursor color的公认答案的作者)进行了一些交谈之后,似乎有一个关于Qt 5.8的错误报告与此相关:

Qt 5.8 no longer allows QPlainTextEdit's cursor color to be set

在撰写本文时被标记为Unresolved。 (当前,Qt5.12是最新版本。)


在长期解释了为什么它不能开箱即用之后,最后给出了一个示例,该示例如何使用定制的游标来实现OP的意图:

#include <QtWidgets>

class TextEdit: public QTextEdit {
  protected:
    virtual void paintEvent(QPaintEvent *pEvent) override;
};

void TextEdit::paintEvent(QPaintEvent *pQEvent)
{
  // use paintEvent() of base class to do the main work
  QTextEdit::paintEvent(pQEvent);
  // draw cursor (if widget has focus)
  if (hasFocus()) {
    const QRect qRect = cursorRect(textCursor());
    QPainter qPainter(viewport());
    qPainter.fillRect(qRect, textColor());
  }
}

class ColorButton: public QPushButton {
  private:
    QColor _qColor;

  public:
    explicit ColorButton(
      const QString &text, const QColor &qColor = Qt::black,
      QWidget *pQParent = nullptr):
      QPushButton(text, pQParent)
    {
      setColor(qColor);
    }
    virtual ~ColorButton() = default;
    ColorButton(const ColorButton&) = delete;
    ColorButton& operator=(const ColorButton&) = delete;

    const QColor& color() const { return _qColor; }
    void setColor(const QColor &qColor)
    {
      _qColor = qColor;
      QFontMetrics qFontMetrics(font());
      const int h = qFontMetrics.height();
      QPixmap qPixmap(h, h);
      qPixmap.fill(_qColor);
      setIcon(qPixmap);
    }

    QColor chooseColor()
    {
      setColor(QColorDialog::getColor(_qColor, this, text()));
      return _qColor;
    }
};

int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  qDebug() << app.style();
  // setup GUI
  QMainWindow qWin;
  qWin.resize(250, 100);
  qWin.setWindowTitle("Test Set Cursor Color");
  TextEdit qTextEdit;
  qWin.setCentralWidget(&qTextEdit);
  qTextEdit.setCursorWidth(QFontMetrics(qTextEdit.font()).averageCharWidth());
  QToolBar qToolBar;
  ColorButton qBtnColor("Text Color",
    qTextEdit.palette().color(QPalette::Text));
  qToolBar.addWidget(&qBtnColor);
  ColorButton qBtnColorBg("Background",
    qTextEdit.palette().color(QPalette::Base));
  qToolBar.addWidget(&qBtnColorBg);
  qWin.addToolBar(&qToolBar);
  qWin.show();
  // install signal handlers
  QObject::connect(&qBtnColor, &QPushButton::clicked,
    [&]() { qTextEdit.setTextColor(qBtnColor.chooseColor()); });
  QObject::connect(&qBtnColorBg, &QPushButton::clicked,
    [&]() {
      QPalette qPal = qTextEdit.palette();
      qPal.setColor(QPalette::Base, qBtnColorBg.chooseColor());
      qTextEdit.setPalette(qPal);
    });
  // runtime loop
  return app.exec();
}

QTextEdit被派生的TextEdit替换为paintEvent()

QTextEdit::paintEvent()中调用TextEdit::paintEvent()来完成主要工作。然后,在textColor中用矩形(重新)绘制光标。 (这只是过度绘制已经渲染的内置文本光标。)

Snapshot in cygwin with X11 Snapshot in Windows 10 with GDI

注意:

小陷阱是QPainterTextEdit::paintEvent()的用法。由于QTextEdit是从QAbstractScrollArea派生的,因此QPainter qPainter(this);是错误的。相反,必须使用QPainter qPainter(viewport());。这是在Qt文档中提到的。为QAbstractScrollArea::paintEvent()

  

注意:如果您打开画家,请确保在viewport()上将其打开。

答案 1 :(得分:1)

根据请求,我的其他answer中的示例程序的Python3 / PyQt5端口:

#!/usr/bin/python3

import sys
from PyQt5.QtCore import QT_VERSION_STR, QRect
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolBar
from PyQt5.QtGui import QPainter, QIcon, QPixmap, QFontMetrics, QPalette
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtWidgets import QPushButton, QColorDialog


class TextEdit(QTextEdit):

    def __init__(self, parent=None):
        QTextEdit.__init__(self, parent)

    def paintEvent(self, event):
        # use paintEvent() of base class to do the main work
        QTextEdit.paintEvent(self, event)
        # draw cursor (if widget has focus)
        if self.hasFocus():
            rect = self.cursorRect(self.textCursor())
            painter = QPainter(self.viewport())
            painter.fillRect(rect, self.textColor())


class ColorButton(QPushButton):

    def __init__(self, text, custom_color, parent=None):
        QPushButton.__init__(self, text, parent)
        self.setColor(custom_color)

    def color(self):
        return self.custom_color

    def setColor(self, custom_color):
        self.custom_color = custom_color
        font_metrics = QFontMetrics(self.font())
        h = font_metrics.height()
        pixmap = QPixmap(h, h)
        pixmap.fill(self.custom_color)
        self.setIcon(QIcon(pixmap))

    def chooseColor(self):
        self.setColor(QColorDialog().getColor(self.custom_color))
        return self.custom_color


if __name__ == '__main__':
    print("Qt Version: {}".format(QT_VERSION_STR))
    app = QApplication(sys.argv)
    print(app.style())
    # build GUI
    win = QMainWindow()
    win.resize(250, 100)
    win.setWindowTitle("Test Set Cursor Color")
    text_edit = TextEdit()
    text_edit.setCursorWidth(QFontMetrics(text_edit.font()).averageCharWidth())
    win.setCentralWidget(text_edit)
    tool_bar = QToolBar()
    btn_color = ColorButton(
        "Text Color", text_edit.palette().color(QPalette.Text))
    tool_bar.addWidget(btn_color)
    btn_color_bg = ColorButton(
        "Background", text_edit.palette().color(QPalette.Base))
    tool_bar.addWidget(btn_color_bg)
    win.addToolBar(tool_bar)
    win.show()
    # install signal handlers
    btn_color.clicked.connect(
        lambda state: text_edit.setTextColor(btn_color.chooseColor()))

    def on_click(state):
        palette = text_edit.palette()
        palette.setColor(QPalette.Base, btn_color_bg.chooseColor())
        text_edit.setPalette(palette)

    btn_color_bg.clicked.connect(on_click)
    # runtime loop
    sys.exit(app.exec_())

输出:

Qt Version: 5.9.3
<PyQt5.QtWidgets.QCommonStyle object at 0x6ffffd8dc18>

Snapshot of testQTextEditCursorColor.py