首页 文章

如何在Windows中使QLineEdit无法编辑

提问于
浏览
18

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

如果我禁用它,它会变成灰色,文本也会变浅 . 问题是,在禁用状态下无法复制文本 .

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

4 回答

  • 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);
    
  • 15

    由于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);
    }
    
  • 3

    我遇到了同样的问题,并从 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_);
        }
    }
    
  • 1

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

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

相关问题