QLineEdit 在激活时更改文本权重



如果处于活动状态,我想使QLineEdit看起来像带有粗体文本的QLabel,如果处于活动状态,则看起来像正常重量的QLineEdit。在我的理解中,"活动"=当文本光标显示并且用户可以输入文本时。

我尝试应用此 css:

QLineEdit {
font-weight: normal;
border: 1px solid black;
}
QLineEdit:!focus {
font-weight: bold;
border: none;
}

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

如果有人能帮助我,我将不胜感激。

您需要获取 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;
}
}
}

当您将行编辑设置为非活动状态时,

//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);

最新更新