【问题标题】:Why doesn't QLineEdit Style change when focused?为什么 QLineEdit Style 在聚焦时不改变?
【发布时间】:2011-10-04 19:00:17
【问题描述】:

我正在使用 Qt 及其样式表开发一个 GUI。在主窗口样式表中,我添加了以下样式:

QLineEdit:focus {
    border: 2px solid #006080;
}

但是当我使用它时,风格并没有像我预期的那样真正改变。但是,如果我将相同的样式表直接放在所需的组件上,它就像魔术一样工作!但是,将样式表放在我可能想要的每个 LineEdit 上并不是一个好主意(这将大大增加添加新组件或更改样式表所需的工作量),也不是通过添加代码行来重新应用样式表,例如 @ 987654322@.

有人知道怎么解决吗?

【问题讨论】:

    标签: qt qtstylesheets


    【解决方案1】:

    奇怪,它可以在我的 Qt 副本上使用 QLineEdit:focus 使用

    QLineEdit:focus
    {
        border: 2px solid #006080;
    }
    

    你确定你在更远的地方没有一个子风格来推翻这个吗?因为它在 MainWindow 上,所以首先要被否决。

    一种可能的解决方法是使用事件过滤器:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        ui->lineEdit->installEventFilter( this );
        ui->lineEdit_2->installEventFilter( this );
    }
    
    ...
    
    bool MainWindow::eventFilter( QObject *object, QEvent *event )
    {
        QLineEdit* edit = qobject_cast< QLineEdit* >( object );
    
        if( edit != NULL )
        {
            if( event->type( ) == QEvent::FocusIn )
            {
                edit->setStyleSheet( QString( "border: 10px solid #000000;" ) );
            }
            else if( event->type( ) == QEvent::FocusOut )
            {
                edit->setStyleSheet( QString( "border: 1px solid #000000;" ) );
            }
        }
    }
    

    当然,QStyleSheets 只是简单的 QString,因此您可以将预定义的样式存储起来以供使用。

    【讨论】:

    • 请不要那样做
    【解决方案2】:

    如果需要,您可以像这样以编程方式设置焦点样式:

    QString styleSheet = "QLineEdit { border: 1px solid; border-color:#dcdcdc; border-radius: 4px;} QLineEdit:focus{border:1px solid gray;}";
    
    yourFancyEdit->setStyleSheet(styleSheet);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-03
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 2020-01-15
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多