[英]How to make a QLineEdit not editable in 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);
}
我遇到了同樣的問題,並從QLineEdit
派生了一個子類QLineView
。 然后,我重新實現了void setReadOnly(bool)
並添加了一個成員var 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_);
}
}
如果其readOnly
屬性設置為true,則可以設置更改QLineEdit
對象顏色的樣式表。
setStyleSheet("QLineEdit[readOnly=\"true\"] {"
"color: #808080;"
"background-color: #F0F0F0;"
"border: 1px solid #B0B0B0;"
"border-radius: 2px;}");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.