如何使QLineEdit在Windows中不可编辑

How to make a QLineEdit not editable in Windows

本文关键字:编辑 Windows 何使 QLineEdit      更新时间:2023-10-16

我使用Qt 5.2,我想使QLineEdit不可编辑。问题是,它看起来不像。当使用setReadOnly(true)时,它保持白色背景,看起来仍然是可编辑的。

如果我禁用它,然后它变成灰色,文本也得到浅灰色。问题是,在禁用状态下,无法从中复制文本。

那么我怎样才能使QLineEdit正确地不可编辑,也使它看起来像它。在Windows中,这样的控件通常是灰色的,但文本保持黑色。当然,我可以手动设置样式,但这意味着它是硬编码的,在其他平台上可能看起来不正确。

将行编辑设置为只读后,您可以将背景和文本颜色设置为您喜欢的任何颜色:

ui->lineEdit->setReadOnly(true);
QPalette *palette = new QPalette();
palette->setColor(QPalette::Base,Qt::gray);
palette->setColor(QPalette::Text,Qt::darkGray);
ui->lineEdit->setPalette(*palette);

既然Nejat用他的答案给我指出了正确的方向,下面是我现在使用的代码:

QPalette mEditable = mGUI->mPathText->palette();  // Default colors
QPalette  mNonEditable = mGUI->mPathText->palette();
QColor col = mNonEditable.color(QPalette::Button);
mNonEditable.setColor(QPalette::Base, col);
mNonEditable.setColor(QPalette::Text, Qt::black);
....
void MyWidget::setEditable(bool bEditable)
{
    mGUI->mPathText->setReadOnly(!bEditable);
    if(bEditable)
        mGUI->mPathText->setPalette(mEditable);
    else
        mGUI->mPathText->setPalette(mNonEditable);
}

如果readOnly属性设置为true,则可以设置样式表来更改QLineEdit对象的颜色。

setStyleSheet("QLineEdit[readOnly="true"] {"
              "color: #808080;"
              "background-color: #F0F0F0;"
              "border: 1px solid #B0B0B0;"
              "border-radius: 2px;}");

我有同样的问题,并从QLineEdit派生了一个子类QLineView。然后,我重新实现了void setReadOnly(bool),并添加了成员变量QPalette activePalette_

QLineEdits调色板存储在函数中。

我重新实现的方法看起来像这样

void QLineView::setReadOnly( bool state ) {
    QLineEdit::setReadOnly(state);
    if (state) {
        QPalette pal = this->activePalette_;
        QColor color = pal.color(QPalette::disabled, this->backgroundRole());
        pal.setColor(QPalette::Active, this->backgroundRole(), color);
        pal.setColor(QPalette::InActive, this->backgroundRole(), color);
        this->setPalette(pal);
    }
    else {
        this->setPalette(this->activePalette_);
    }
}