How to control QAction buttons spacing in QToolBar?
Asked Answered
H

1

7

enter image description here

With four QAction buttons added to QToolBar what widgets properties need to be set and to what value to make no spacing between the buttons. So each button is placed side by side? As it can be seen from the example posted below I've tried to achieve zero spacing with:

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

but it makes no difference and the buttons are still spaced from each other....

import sys
from PyQt4.QtGui import *

class Window(QMainWindow):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):               

        textEdit = QTextEdit()
        self.setCentralWidget(textEdit)

        btn1 = QAction(QIcon('icons/btn1.png'), 'Button 01', self)
        btn2 = QAction(QIcon('icons/btn2.png'), 'Button 02', self)
        btn3 = QAction(QIcon('icons/btn3.png'), 'Button 03', self)
        btn3.setEnabled(False)

        btn1.setShortcut('Ctrl+Q')
        btn1.triggered.connect(self.close)

        toolbar = self.addToolBar('Exit')
        toolbar.addAction(btn1)
        toolbar.addAction(btn2)
        toolbar.addAction(btn3)
        toolbar.addSeparator()

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


        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Main window')    
        self.show()

def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main() 
Huynh answered 18/1, 2015 at 5:59 Comment(0)
S
15

From the stylesheet examples for QToolBar:

spacing: 3px; /* spacing between items in the tool bar */

So this should do the trick:

toolbar.setStyleSheet("QToolBar{spacing:0px;}");
Subsocial answered 29/1, 2015 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.