I'm writing a GUI with PyQt5 and I realized that the setContentsMargins
method doesn't work properly in a Tab widget. Inside of it there is always a 9px margin for each side (see the attached screenshot):
Here is an example (inside the Tab1 I put a TreeView widget with a using the QVBoxLayout):
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTabWidget, QVBoxLayout, QTreeView
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 tabs'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.show()
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")
self.tab1.layout = QVBoxLayout(self)
self.TreeView=QTreeView()
self.tab1.layout.addWidget(self.TreeView)
self.tab1.setLayout(self.tab1.layout)
self.tab1.setStyleSheet("background-color: red")
self.tab1.setContentsMargins(-4, -4, -4, -4) # this instruction doesn't work! there is always a default margin (9px for each side)!
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
As you can see, if I use the instruction self.tab1.setContentsMargins(10, 10, 10, 10)
all the margins, will be 19px (9+10), but what about if a want 5px? The instruction self.tab1.setContentsMargins(-4, -4, -4, -4)
doesn't work.
The additional margin is from the widget's layout. Set it to zero or any other value:
self.tab1.layout.setContentsMargins(0, 0, 0, 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.