I have a pushbutton to add a tab in a QTabWidget. But when I change the button's size, it's not in the corner anymore. So how can I bring it to the corner like in the first picture?
Not change size:
Change size:
Here is my code:
from PyQt4 import QtGui, QtCore
class PlaylistTable(QtGui.QWidget):
def __init__(self):
super(PlaylistTable, self).__init__()
self.playlistTable = QtGui.QTableWidget(self)
self.playlistTable.setFrameShape(QtGui.QFrame.NoFrame)
self.playlistTable.setFrameShadow(QtGui.QFrame.Sunken)
self.playlistTable.setLineWidth(0)
self.playlistTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.playlistTable.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
self.playlistTable.setHorizontalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
self.playlistTable.setShowGrid(True)
self.playlistTable.setGridStyle(QtCore.Qt.SolidLine)
self.playlistTable.setWordWrap(True)
self.playlistTable.setCornerButtonEnabled(True)
self.playlistTable.verticalHeader().setVisible(False)
class CustomTabWidget(QtGui.QTabWidget):
"""Tab Widget that that can have new tabs easily added to it."""
def __init__(self, parent=None):
super(CustomTabWidget, self).__init__(parent)
# QtGui.QTabWidget.__init__(self, parent)
# Tab Bar
self.tab = QtGui.QTabBar()
self.setTabBar(self.tab)
# Properties
self.setMovable(True)
self.setTabsClosable(True)
self.plusButton = QtGui.QPushButton("+")
self.plusButton.setFixedSize(QtCore.QSize(22, 22))
self.setCornerWidget(self.plusButton)
# Signals
self.connect(self.plusButton, QtCore.SIGNAL('clicked()'), self.addTab)
# self.tab.plusClicked.connect(self.addTab)
self.tab.tabMoved.connect(self.tab.moveTab)
self.tabCloseRequested.connect(self.removeTab)
def addTab(self):
string = QtCore.QString.fromUtf8("Playlist")
tab = PlaylistTable()
super(CustomTabWidget, self).addTab(tab, string)
class AppDemo(QtGui.QMainWindow):
def __init__(self):
super(AppDemo, self).__init__()
self.centralwidget = QtGui.QWidget(self)
self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setContentsMargins(0, -1, 0, -1)
self.playlist_manager = CustomTabWidget(self.centralwidget)
self.horizontalLayout.addWidget(self.playlist_manager)
self.playlist_manager.addTab()
self.setCentralWidget(self.centralwidget)
self.show()
# end class AppDemo
def main():
import sys
app = QtGui.QApplication(sys.argv)
w = AppDemo()
w.setWindowTitle('AppDemo')
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I'm guessing the reason is this, from QTabWidget Documentation:
The geometry of the widget is determined
based on the widget's sizeHint() and the style().
If you print the sizeHint() of the QPushButton you will see that width never goes below a certain value.
I've found an alternative is to use a QToolButton which can do everything (even more) a QPushButton does.
self.plusButton = QtGui.QToolButton(self)
self.plusButton.setText("+")
Related
I am writing a QTabwidget with only two tabs. But the tab headers (name) are not fitting the QTabwidget width. I want to fit the length of the tab bar (two tab headers)
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QMainWindow):
def __init__(self):
super().__init__()
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()
""" Here I want to fit the two tab
headers withthe QTabwidget width
"""
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")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
The size of tabs is computed using the hints given by the current QStyle.
Since QTabWidget uses the sizeHint of the tab bar to set the tab bar size and the sizeHint is usually based on the tabSizeHint(), you have to reimplement both:
sizeHint() is required in order to provide a width (or height) that is the same as the parent;
tabSizeHint() takes into account the base implementation of sizeHint() to compute the hint based on the contents of the tabs, and if it's less than the current size it suggests a size based on the available space divided by the tab count;
class TabBar(QtWidgets.QTabBar):
def sizeHint(self):
hint = super().sizeHint()
if self.isVisible() and self.parent():
if not self.shape() & self.RoundedEast:
# horizontal
hint.setWidth(self.parent().width())
else:
# vertical
hint.setHeight(self.parent().height())
return hint
def tabSizeHint(self, index):
hint = super().tabSizeHint(index)
if not self.shape() & self.RoundedEast:
averageSize = self.width() / self.count()
if super().sizeHint().width() < self.width() and hint.width() < averageSize:
hint.setWidth(averageSize)
else:
averageSize = self.height() / self.count()
if super().sizeHint().height() < self.height() and hint.height() < averageSize:
hint.setHeight(averageSize)
return hint
# ...
self.tabWidget = QtWidgets.QTabWidget()
self.tabWidget.setTabBar(TabBar(self.tabWidget))
Do note that this is a very basic implementation, there are some situations for which you might see the scroll buttons with very long tab names, even if theoretically there should be enough space to see them.
Inspired by this answer, I think you can override showEvent (and even resizeEvent) to calculate the new width and set it through stylesheets.
It is not canonical but it does the job.
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTabWidget, QVBoxLayout
class App(QMainWindow):
def __init__(self):
super().__init__()
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.tabs.tabBar().setExpanding(True)
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")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def resizeEvent(self, event):
super().resizeEvent(event)
self._set_tabs_width()
def showEvent(self, event):
super().showEvent(event)
self._set_tabs_width()
def _set_tabs_width(self):
tabs_count = self.tabs.count()
tabs_width = self.tabs.width()
tab_width = tabs_width / tabs_count
css = "QTabBar::tab {width: %spx;}" % tab_width
self.tabs.setStyleSheet(css)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
I found some code on here that shows an example of how you can get the window to resize when the widget is hidden, and it works for me. Here is the code:
from PyQt4 import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
super(MainWindow, self).__init__()
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def startup(self):
self.show()
sys.exit(self.app.exec_())
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
myApp = MainWindow()
myApp.startup()
I then tried to modify this to match my existing code by separating the mainWindow class and the widget class. Here is the code that does that.
from PySide import QtGui,QtCore
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.w = testW(self)
self.setCentralWidget(self.w)
self.show()
class testW(QtGui.QWidget):
def __init__(self,parent):
super(testW,self).__init__()
self.parent = parent
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.button.setChecked(True);
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myApp = MainWindow()
sys.exit(app.exec_())
#time.sleep(1)
Running the first code does what I want it to. After I hide the widget, the window resizes to the correct size. The second implementation of the code does not shrink and expand the window when I hide and show the widget. Is this because the MainWindow is in a separate class?
Use size policies for your widgets. For your example you can change UI creation code as follows:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.w = testW(self)
self.w.setSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding,
QtWidgets.QSizePolicy.MinimumExpanding
)
self.setCentralWidget(self.w)
self.show()
Please note new setSizePolicy call which say Qt layout engine how to change the size of your widget according to its content.
Unfortunately QMainWindow does not respect sizeHint automatically, but it is calculated properly, so you can adjustSize manually:
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.parent.adjustSize)
You do not need to resize your widget itself, because it will be resized according to the policy. Even sizeHint will be calculated automatically so you need only to call adjustSize of QMainWindow.
PS: I used PySide2 instead of PySide so the imports are different a little bit:
from PySide2 import QtWidgets, QtCore
Baseline
How I want to create
Hi
I have a simple PyQT5 app. The main window is a QMainWindow which houses a QWidget. The Layout of the QWidget is as follows:
Class Canvas(QWidget):
def __init__(self):
super().__init__()
self.ListOfPlots = []
self.outFile = "temp.prb"
self.initUI()
def initUI(self):
self.headLabel = QLabel("List of Plots:")
self.label = QLabel("",self)
self.setAcceptDrops(True)
self.createPushButtons()
hbox = QHBoxLayout() #Horizontal Layout
#hbox.addStretch(1)
hbox.addWidget(self.combineButton)
hbox.addWidget(self.openButton)
hbox.addWidget(self.resetButton)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.headLabel)
self.vbox.addWidget(self.label)
self.vbox.addLayout(hbox) ## The horizontal box is placed into vertical layout
self.setLayout(self.vbox)
I want to create a translucent drop area as shown in the second picture with a label indicating drop files here. What would be the most suitable way to do it?
The entire widget is ok to allow drops. I just want a box indicating it is ok to drop here (like an indicator).
You can use dynamic properties to trigger an indicator when it's okay to drop. If you need the background to be semi-transparent, use rgba for your widget's stylesheet background property. background:rgba(255,255,255,90)
from PySide2 import QtWidgets
import sys
from PySide2.QtWidgets import QWidget, QGridLayout, QFrame
class DropZone(QFrame):
def __init__(self, parent=None):
QFrame.__init__(self)
self.setFixedSize(200, 200)
self.setAcceptDrops(True)
self.setObjectName('DropZone')
self.setStyleSheet(
'QFrame#DropZone[Dropindicator=true]{border:3px solid green;background:darkorange;}\nQFrame#DropZone{background:orange;}')
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('text/plain'):
self.setProperty('Dropindicator',True)
print(event.mimeData().text())
self.setStyle(self.style())
...
event.accept()
else:
event.ignore()
def dropEvent(self, event):
event.accept()
if event.isAccepted():
self.setProperty('Dropindicator',False)
self.setStyle(self.style())
class Widget( QWidget):
def __init__(self,parent=None):
QWidget.__init__(self)
gl = QGridLayout()
self.setLayout(gl)
self.dz = DropZone()
self.dz.setParent(self)
gl.addWidget(self.dz)
self.setLayout(gl)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
I have a tab widget that contains table widgets for each tab, and I also have a dock widget with options. One of the options is the column count, and I want to change it as soon as the column count spin box value changes. But when switching to a different tab, I'd like the spin box value (and all other options) to reset / switch to that specific tab's settings.
My question is how to best do this and still have the options as a dock widget. I could store all settings as variables for each tab widget and then change the value each time a new tab is opened, I guess, but maybe there is a better solution.
from PyQt5 import QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__()
self.__setup__()
def __setup__(self):
self.resize(400, 400)
tabWidget = TabWidget(self)
self.setCentralWidget(tabWidget)
options = Options(self)
optionsDock = QtWidgets.QDockWidget()
optionsDock.setWidget(options)
optionsDock.setWindowTitle("Options")
self.addDockWidget(QtCore.Qt.TopDockWidgetArea, optionsDock)
options.spinBox_columns.valueChanged.connect(lambda: tabWidget.tabWidget.currentWidget().
setColumnCount(options.spinBox_columns.value()))
class Options(QtWidgets.QWidget):
def __init__(self, parent):
super(Options, self).__init__(parent)
self.__setup__()
def __setup__(self):
self.spinBox_columns = QtWidgets.QSpinBox()
self.spinBox_columns.setValue(1)
self.spinBox_columns.setMinimum(1)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.spinBox_columns)
self.setLayout(layout)
class TabWidget(QtWidgets.QWidget):
def __init__(self, parent):
super(TabWidget, self).__init__(parent)
self.__setup__()
def __setup__(self):
self.tabWidget = QtWidgets.QTabWidget()
for i in range(3):
widget = QtWidgets.QTableWidget()
widget.setColumnCount(1)
widget.setRowCount(3)
self.tabWidget.addTab(widget, "Column " + str(i))
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.tabWidget)
self.setLayout(layout)
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
You have to connect the currentChanged signal provided by the index of the tab, then use the widget() method to obtain the index associated with that index, then access its QTabWidget and obtain the number of columns using it to place the value to the QSpinBox.
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.__setup__()
def __setup__(self):
self.resize(400, 400)
tabWidget = TabWidget(self)
self.setCentralWidget(tabWidget)
options = Options(self)
optionsDock = QtWidgets.QDockWidget()
optionsDock.setWidget(options)
optionsDock.setWindowTitle("Options")
self.addDockWidget(QtCore.Qt.TopDockWidgetArea, optionsDock)
tabWidget.tabWidget.currentChanged.connect(lambda index: options.spinBox_columns.
setValue(tabWidget.tabWidget.widget(index).columnCount()))
options.spinBox_columns.valueChanged.connect(lambda value: tabWidget.tabWidget.currentWidget().
setColumnCount(value))
I have a QGroupBox with a title '123'. Inside the QGroupBox, there should be a QScrollArea. That means that the title '123' of QGrouBox should be outside of the QScrollArea.
My sample codes are as below.
import sys
import PyQt4
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Example(QWidget):
def __init__(self, parent = None):
super().__init__()
btn = QPushButton('button')
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(btn)
groupbox = QGroupBox('123')
groupbox.setLayout(scroll)
self.show()
def main():
app = QApplication(sys.argv)
main = Example()
main.show()
sys.exit(app.exec_())
As you can see above, now it returns TypeError: setLayout(self, QLayout): argument 1 has unexpected type 'QScrollArea'.
I'm just wondering if this is achievable? Thanks!!
When you want to add the content to a QGroupBox you must do through a layout that contains the necessary widgets, in this case as it is only a widget we can use any layout, and in this layout we add the widget that this case is the QScrollArea as sample then:
class Example(QWidget):
def __init__(self, parent = None):
super().__init__()
self.setLayout(QVBoxLayout())
btn = QPushButton('button')
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(btn)
groupbox = QGroupBox('123', self)
groupbox.setLayout(QVBoxLayout())
groupbox.layout().addWidget(scroll)
self.layout().addWidget(groupbox)
Screenshot: