【问题标题】:How to make a QLineEdit not editable in Windows如何使 QLineEdit 在 Windows 中不可编辑
【发布时间】:2023-04-06 13:50:01
【问题描述】:

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

如果我禁用它,它会变成灰色,文本也会变成浅灰色。问题是,无法从中复制文本,处于禁用状态。

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

【问题讨论】:

  • 灰色用于“禁用”小部件,而不是只读小部件。它们是不同的想法。

标签: c++ qt readonly qlineedit


【解决方案1】:

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

ui->lineEdit->setReadOnly(true);

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

【讨论】:

  • 这不是我想要的,但它引导我走向了正确的方向。 :) 谢谢。
【解决方案2】:

既然 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::WindowQt::black 更改为QPalette::WindowText 以实现便携性。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

    QLineEdits 调色板存储在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_);
        }
    }
    

    【讨论】:

    • 为什么投反对票?我没有否决它,但我的直觉是不需要它,因为您可以执行上述解决方案,或者只使用 qlabel(具有更改的属性)而不创建新的子类。
    • 但是标签也可以显示复杂的文本,例如带有格式的 HTML 吗?
    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2010-09-10
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多