简体   繁体   中英

Set gray background color for read-only QPlainTextEdit

Right now a read-only plain text edit has a white coloring, which does not make it obvious that it's read-only. I need to make my read-only plain text edit to be "gray". However, by gray I mean the default system color corresponding to it, instead of a hard-coded RGB(127, 127, 127).

The reason I can't just disable the widget is that I want the user to be able to select and copy the text. This is possible with read-only edit boxes but not if they are disabled.

Example screenshot of what I have in mind:

在此处输入图片说明

Very late response, but just looking for the same. Above solution works very nicely, but I guess the following code is more qt'isch:

// read-only PlainTextEdit with gray background
QColor mainWindowBgColor = palette().color(QPalette::Window);
// for the current widget
setStyleSheet(QString("QPlainTextEdit[readOnly=\"true\"] { background-color: %0 }").arg(mainWindowBgColor.name(QColor::HexRgb)));

// or application wide do:
qApp->setStyleSheet(QString("QPlainTextEdit[readOnly=\"true\"] { background-color: %0 }").arg(mainWindowBgColor.name(QColor::HexRgb)));

Advantage is that you need to do it only once, but gaining a consistent look and feel. Please pay attention of using the complex selector in the square brackets. Disadvantage is, but that's the same issue with the above code, that changing the OS design/profile will not have an effect until you re-execute the code (most probably doing a restart of your application). - Its very sad that QtDesigner does not offer a simple way to do that - or I did not yet figure out how to do it.

And finally as application wide one-liner for all elements having a readOnly attribute set:

qApp->setStyleSheet(QString("[readOnly=\"true\"] { background-color: %0 }").arg(qApp->palette().color(QPalette::Window).name(QColor::HexRgb)));

After some Googling and some experimenting, I found out how to do it:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QPalette readOnlyPalette = ui->plainTextEdit->palette();
    QColor mainWindowBgColor = palette().color(QPalette::Window);
    readOnlyPalette.setColor(QPalette::Base, mainWindowBgColor);
    ui->plainTextEdit->setPalette(readOnlyPalette);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM