我正在使用Qt 5.2,我想让 QLineEdit 不可编辑 . 这个问题是它看起来不像 . 当使用 setReadOnly(true) 时,它保持白色背景,看起来仍然可以编辑 .
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); }
我遇到了同样的问题,并从 QLineEdit 派生了一个子类 QLineView . 然后,我重新实现了 void setReadOnly(bool) 并添加了一个成员var QPalette activePalette_
QLineView
void setReadOnly(bool)
QPalette activePalette_
将 QLineEdit 的调色板存储在ctor中 .
我重新实现的方法就像这样
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_); } }
如果 QLineEdit 属性的 readOnly 属性设置为true,则可以设置更改 QLineEdit 对象颜色的样式表 .
readOnly
setStyleSheet("QLineEdit[readOnly=\"true\"] {" "color: #808080;" "background-color: #F0F0F0;" "border: 1px solid #B0B0B0;" "border-radius: 2px;}");
4 回答
在进行只读行编辑后,您可以将背景和文本颜色设置为您喜欢的任何颜色:
由于Nejat用他的答案指出了正确的方向,这里是我现在使用的代码:
我遇到了同样的问题,并从
QLineEdit
派生了一个子类QLineView
. 然后,我重新实现了void setReadOnly(bool)
并添加了一个成员varQPalette activePalette_
将
QLineEdit
的调色板存储在ctor中 .我重新实现的方法就像这样
如果
QLineEdit
属性的readOnly
属性设置为true,则可以设置更改QLineEdit
对象颜色的样式表 .