QLineEdit在激活时更改文本权重

时间:2017-11-21 20:27:02

标签: c++ css qt

我希望QLineEdit看起来像QLabel,如果它处于非活动状态,则使用粗体文字,如果活跃,则QLineEdit正常体重QLineEdit { font-weight: normal; border: 1px solid black; } QLineEdit:!focus { font-weight: bold; border: none; } 。根据我的理解"活跃" =显示文本光标时,用户可以输入文本。

我尝试应用此css:

{{1}}

边框按预期工作,但font-weight始终为粗体。 我正在考虑创建我的类以处理激活事件,但无法找到与之相关的任何内容。

如果有人可以帮助我,我将非常感激。

2 个答案:

答案 0 :(得分:1)

您需要获取focusChanged事件的自定义插槽。在那里你可以改变这样的字体:

QFont font = ui->lineEdit_search->font();
font.setWeight(QFont::Bold); // or
font.setWeight(QFont::Normal);
ui->lineEdit_search->setFont(font);

我在这里处理LineEdit搜索框的示例,但您必须使用粗体文本对其进行自定义。

void MainWindow::focusChanged(QWidget* old, QWidget* now)
{
    if(now != NULL &&
       now->objectName() == "lineEdit_search")
    {
        if(ui->lineEdit_search->text() == tr("Search..."))
        {
            ui->lineEdit_search->clear();

            QPalette *palette = new QPalette();
            palette->setColor(QPalette::Text,Qt::black);
            ui->lineEdit_search->setPalette(*palette);

            delete palette;
        }
    }
    else if(old != NULL &&
            old->objectName() == "lineEdit_search")
    {
        if(ui->lineEdit_search->text().isEmpty())
        {
            ui->lineEdit_search->setText(tr("Search..."));

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

            delete palette;
        }
    }
}

答案 1 :(得分:0)

当您将线路编辑变为无效时,

//Set your line edit to read only
yourLineEdit->setReadOnly(true);

//Get your widget background color
const QColor clr = this->palette().color(QWidget::backgroundRole());

//Set the widget background color to both the line edit background and its border
QString backGroundstyle = "background-color: rgb(%1, %2, %3);";
QString borderStyle = "border: 1px solid rgb(%1, %2, %3);";

yourLineEdit->setStyleSheet(backGroundstyle.arg(clr.red()).arg(clr.green()).arg(clr.blue()) + borderStyle.arg(clr.red()).arg(clr.green()).arg(clr.blue()));

当您将线路编辑变为活动

//Make your line edit read-write
yourLineEdit->setReadOnly(false);

//Bring back your styles.
QString backGroundstyle_active = "background-color: white;";
QString borderStyle_active = "border: 1px solid black;";

yourLineEdit->setStyleSheet(backGroundstyle_active + borderStyle_active);