alphanumeric
alphanumeric

Reputation: 19329

How Not to space the widgets within QHBoxLayout

While using:

layout = QtGui.QHBoxLayout()
layout.addWidget(QtGui.QPushButton())
layout.addWidget(QtGui.QPushButton())
layout.addWidget(QtGui.QPushButton())

the buttons get automatically spaced out within the width of the QHBoxLayout. Instead I would like the buttons to be placed edge by edge next to each other. I have tried to use :

    layout.setContentsMargins(0, 0, 0, 0)
    layout.importLayout.setSpacing(0) 

but it has no effect on buttons spacing. What attribute of the QHBoxLayout needs to be set to override the auto spacing?

Upvotes: 3

Views: 5709

Answers (2)

NoDataDumpNoContribution
NoDataDumpNoContribution

Reputation: 10860

Your approach was already the right one. No contents margins on the layout as well as no spacing on the layout will put the buttons extremely close with a spacing of about 2 pixels. Negative margins set by a stylesheet can get the buttons further together but I don't recommend it because it doesn't look nice.

from PySide import QtGui

app = QtGui.QApplication([])
window = QtGui.QWidget()
window.setStyleSheet('QPushButton{margin-left:-1px;}') # remove this line if you want to have a tiny bit of spacing left

layout = QtGui.QHBoxLayout(window)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))

window.show()

app.exec_()

Upvotes: 5

thecreator232
thecreator232

Reputation: 2185

I believe you wish to have negligible spacing between the pushButtons something like this.

enter image description here

Try using layout.setSpacing(0)

self.horizontalLayout = QtGui.QHBoxLayout(self.widget)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setMargin(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtGui.QPushButton(self.widget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.horizontalLayout.addWidget(self.pushButton_2)
self.pushButton_3 = QtGui.QPushButton(self.widget)
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.horizontalLayout.addWidget(self.pushButton_3)

Upvotes: 2

Related Questions