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,这就是间隙的来源。只需要两步就能解决:
- 设置布局的spacing为0
在创建h = QtGui.QHBoxLayout()之后,添加一行代码:
h.setSpacing(0)
这会完全移除两个控件之间的布局间距。
- 优化样式表(可选但更规范)
你当前用*选择器会影响所有子控件,建议直接指定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
相关产品推荐
相关产品推荐

