烦人的背景位置问题

Jas*_*enX 3 qt

这是它的样子

这是我的样式表:

QLineEdit#SearchBarEditBox {
    background: white;
    background-image: url(:/images/magnifyingGlass.png);
    background-repeat: no-repeat;
    background-position: 5px 5px;
}
Run Code Online (Sandbox Code Playgroud)

我的问题:“背景位置”仅接收“顶部/底部/右侧/左侧”值。任何使用数字绝对值的尝试都会立即导致我的图像的“顶部中心”理由。这里要疯了....

LHM*_*ies 5

Qt 样式表不实现完整的 CSS,您只能使用center/top/left/bottom/rightfor background-position.

请参阅Qt 样式表参考中的背景位置对齐方式


cle*_*dre 5

虽然这是一个老问题,但我想为那些现在仍然有同样问题的人解答。

我使用以下background-origin属性解决了这个问题:

小部件的背景矩形,与背景位置和背景图像结合使用。[...] 如果未指定此属性,则默认为填充。

解决问题的完整样式表是:

QLineEdit#SearchBarEditBox{
    background-color: #FFFFFF;
    border-radius: 12px;
    border: 1px solid #DEDEDE;
    padding: 4px 4px 4px 10px; /* top - right - bottom - left */
    background-image: url(:/icons/search.png);
    background-repeat: no-repeat;
    background-position: left center;
    background-origin: content; /* the left margin of background image will 'obey' the padding-left defined up above (10px) */
}
Run Code Online (Sandbox Code Playgroud)

结果

仅用于测试,尝试将填充从“10px”更改为“30px”,看看会发生什么。

根据 @Soyal7 评论更新:

根据您使用的组件的类型,为了防止文本重叠,还需要做一件事:

QLineEdit:用于ui->SearchBarEditBox->setTextMargins(20, 0, 0, 0);添加文本左边距;

QPushButton:您可以子类化QPushButton并重新实现paintEvent()方法,或者如果您想要更简单的解决方法,只需在文本前添加一些空格即可。

QLabel:使用indent这样的属性:

设置左边距

希望能帮助到你 :)