You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt4:如何消除水平布局中两个QLineEdit的边框间隙

如何让PyQt4中两个QLineEdit的边框无缝贴合?

我在PyQt4里用QHBoxLayout添加了两个自定义QLineEdit控件,把它们的样式设置成只显示上下红色边框,但两个控件的边框之间总是有间隙,怎么才能让它们无缝贴合呢?以下是我的测试代码:

import sys
from PyQt4 import QtGui
class Edit(QtGui.QLineEdit):
    def __init__(self, text):
        super(Edit, self).__init__()
        self.setText(text)
        self.setFixedSize(200, 40)
        self.setStyleSheet("""*{border-width: 1px; border-style: solid; border-color: red; border-left:none; border-right:none; margin:0px; padding:0px; }""")
class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()
    def initUI(self):
        h = QtGui.QHBoxLayout()
        a = Edit("Hello World")
        b = Edit("Hello World")
        h.addWidget(a)
        h.addWidget(b)
        h.setContentsMargins(0, 0, 0, 0)
        h.addStretch(1)
        self.setLayout(h)
        self.setGeometry(100, 100, 500, 500)
        self.show()
def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
if __name__ == '__main__':
    main()

解决方案:

问题出在QHBoxLayout默认的控件间距上,你已经设置了布局的contentsMargins为0,但布局本身还会给控件之间留默认的spacing,这就是间隙的来源。只需要两步就能解决:

  1. 设置布局的spacing为0
    在创建h = QtGui.QHBoxLayout()之后,添加一行代码:
h.setSpacing(0)

这会完全移除两个控件之间的布局间距。

  1. 优化样式表(可选但更规范)
    你当前用*选择器会影响所有子控件,建议直接指定QLineEdit来避免意外影响,样式表可以改成:
QLineEdit {
    border-width: 1px;
    border-style: solid;
    border-color: red;
    border-left: none;
    border-right: none;
    margin: 0px;
    padding: 0px;
}

修改后的完整代码:

import sys
from PyQt4 import QtGui
class Edit(QtGui.QLineEdit):
    def __init__(self, text):
        super(Edit, self).__init__()
        self.setText(text)
        self.setFixedSize(200, 40)
        self.setStyleSheet("""QLineEdit{border-width: 1px; border-style: solid; border-color: red; border-left:none; border-right:none; margin:0px; padding:0px; }""")
class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()
    def initUI(self):
        h = QtGui.QHBoxLayout()
        # 设置控件间距为0
        h.setSpacing(0)
        a = Edit("Hello World")
        b = Edit("Hello World")
        h.addWidget(a)
        h.addWidget(b)
        h.setContentsMargins(0, 0, 0, 0)
        h.addStretch(1)
        self.setLayout(h)
        self.setGeometry(100, 100, 500, 500)
        self.show()
def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
if __name__ == '__main__':
    main()

这样修改后,两个QLineEdit的上下边框就会完全无缝贴合在一起了,中间不会再有间隙~

内容的提问来源于stack exchange,提问作者redj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:29:12