我正在使用Qt 5.2,想要让QLineEdit
不可编辑。问题是,它看起来仍然可以编辑。当调用setReadOnly(true)
时,它的背景仍然是白色,看起来可以编辑。
如果我将其禁用,它就会变成灰色,文本也会变成浅灰色。问题是,在禁用状态下,无法从中复制文本。
那么,如何使QLineEdit
真正不能编辑,并使其外观符合不可编辑状态。在Windows上,这种控件通常是灰色的,但文本保持黑色。当然,我可以手动设置样式,但这意味着它是硬编码的,并且可能在其他平台上显示不正确。
我正在使用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);
}
QPalette::Button
更改为 QPalette::Window
,并将 Qt::black
更改为 QPalette::WindowText
以提高可移植性。 - Mad Physicist如果QLineEdit
对象的readOnly
属性被设置为true,您可以设置样式表来改变其颜色。
setStyleSheet("QLineEdit[readOnly=\"true\"] {"
"color: #808080;"
"background-color: #F0F0F0;"
"border: 1px solid #B0B0B0;"
"border-radius: 2px;}");
我曾经遇到同样的问题并创建了一个子类QLineView
,继承自QLineEdit
。然后,我重新实现了void setReadOnly(bool)
方法,并添加了一个成员变量QPalette activePalette_
。
在构造函数中存储QLineEdit
的调色板。
我的重新实现的方法如下:
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_);
}
}