PyQt4 QTableWidget: Set row width and column height to fill parent widget - python

I am working on a fairly simply PyQt program which basically is just a QTableWidget full of items. My goal is for the width and height of the items to automatically resize based on the size of the parent QTableWidget. For example, if I resize the window smaller, the items width and height should decrease in size but there should remain the same number of items and the items should still completely fill the parent QTableWidget. As you see, I am currently using setColumnWidth and setRowHeight to manually set the width and height.
I have tried the suggestions in the following Stack Overflow questions, as well as many other questions and websites, none of which do what I am attemping to do.
1. How to make qtablewidgets columns assume the maximum space
2. pyqt how to maximize the column width in a tableview
Here is the code I am using currently:
from PyQt4 import QtGui, QtCore
import PyQt4.Qt
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
super(Window, self).__init__()
self.setWindowState(QtCore.Qt.WindowMaximized)
self.table = QtGui.QTableWidget(rows, columns, self)
self.table.verticalHeader().setVisible(False)
self.table.horizontalHeader().setVisible(False)
# this is what I am currently using to set the row and column size
for x in range(columns):
self.table.setColumnWidth(x, 13)
for x in range(rows):
self.table.setRowHeight(x, 13)
for row in range(rows):
for column in range(columns):
item = QtGui.QTableWidgetItem()
self.table.setItem(row, column, item)
layout = QtGui.QGridLayout(self)
layout.addWidget(self.table, 0, 0, 1, 6)
self.show()
def main():
import sys
app = QtGui.QApplication(sys.argv)
window = Window(54, 96)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I appoligize for the length of this question, but I wanted to make my question very clear. Thank you all in advance for your help!

You can do this using a QItemDelegate and overriding the sizeHint method. Then override the resizeEvent and showEvent methods of you main widget to update the sizes of each cell whenever the widget is resized.
import sys
from PyQt4 import QtGui, QtCore
class MyDelegate(QtGui.QItemDelegate):
def __init__(self, parent, table):
super(MyDelegate, self).__init__(parent)
self.table = table
def sizeHint(self, option, index):
# Get full viewport size
table_size = self.table.viewport().size()
gw = 1 # Grid line width
rows = self.table.rowCount() or 1
cols = self.table.columnCount() or 1
width = (table_size.width() - (gw * (cols - 1))) / cols
height = (table_size.height() - (gw * (rows - 1))) / rows
return QtCore.QSize(width, height)
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
super(Window, self).__init__()
self.lay = QtGui.QVBoxLayout()
self.setLayout(self.lay)
self.table = QtGui.QTableWidget(rows, columns, self)
self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lay.addWidget(self.table)
self.delegate = MyDelegate(self, self.table)
self.table.setItemDelegate(self.delegate)
def showEvent(self, event):
super(Window, self).showEvent(event)
self.resizeTable()
def resizeTable(self):
self.table.resizeRowsToContents()
self.table.resizeColumnsToContents()
def resizeEvent(self, event):
super(Window, self).resizeEvent(event)
self.resizeTable()

Related

QComboBox show whole row of QTreeView

I want to use QtreeView to organize the data shown by a QComboBox. As you can see in my example, creating the box and setting up data works so far.
But my problem is, that the combobox itself only shows the first argument and not the whole line. what I want to have is, that there is shown the whole row, not only the first item of the row.
Is this maybe related to the fact, that each cell is selectable? Do I have to prohibit to select items at the end of the tree branch?
How can I achieve this while adding the elements to the QtreeView-data?
minimal example:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
data = [['a','b','c'],['d','e','f'],['g','h','i']]
class MainWindow(QMainWindow):
dispatcher = 0
def __init__(self):
super().__init__()
# buil UI
self.init_ui()
def init_ui(self):
# layout
self.box_window = QVBoxLayout()
# content
model = QStandardItemModel(len(data),len(data[0]))
row = 0
for r in data:
col = 0
for item in r:
model.setData(model.index(row, col), item)
col += 1
row += 1
tree_view = QTreeView()
tree_view.setHeaderHidden(True)
tree_view.setRootIsDecorated(False)
tree_view.setAlternatingRowColors(True)
combobox = QComboBox()
combobox.setMinimumSize(250,50)
combobox.setView(tree_view)
combobox.setModel(model)
self.box_window.addWidget(combobox)
self.box_window.addStretch()
# build central widget and select it
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.centralWidget().setLayout(self.box_window)
# show window
self.setGeometry(50,50,1024,768)
self.setWindowTitle("Test")
self.show()
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
A possible solution is to concatenate the texts in the row and set as the text to be painted:
class ComboBox(QComboBox):
def paintEvent(self, event):
painter = QStylePainter(self)
painter.setPen(self.palette().color(QPalette.Text))
# draw the combobox frame, focusrect and selected etc.
opt = QStyleOptionComboBox()
self.initStyleOption(opt)
values = []
for c in range(self.model().columnCount()):
index = self.model().index(self.currentIndex(), c, self.rootModelIndex())
values.append(index.data())
opt.currentText = " ".join(values)
painter.drawComplexControl(QStyle.CC_ComboBox, opt)
# draw the icon and text
painter.drawControl(QStyle.CE_ComboBoxLabel, opt)

How to resize square children widgets after parent resize in Qt5?

I want to do board with square widgets. When I run code it creates nice board but after resize it become looks ugly. I am trying resize it with resize Event but it exists (probably some errors). I have no idea how to resize children after resize of parent.
Children widgets must be squares so it is also problem since I can not use auto expand. Maybe it is simple problem but I can not find solution. I spend hours testing different ideas but it now works as it should.
This what I want resize (click maximize):
After maximize it looks ugly (I should change children widget but on what event (I think on resizeEvent but it is not works) and how (set from parent or children cause program exit).
This is my minimize code:
import logging
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QFont, QPaintEvent, QPainter
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout
class Application(QApplication):
pass
class Board(QWidget):
def square_size(self):
size = self.size()
min_size = min(size.height(), size.width())
min_size_1_8 = min_size // 8
square_size = QSize(min_size_1_8, min_size_1_8)
logging.debug(square_size)
return square_size
def __init__(self, parent=None):
super().__init__(parent=parent)
square_size = self.square_size()
grid = QGridLayout()
grid.setSpacing(0)
squares = []
for x in range(8):
for y in range(8):
square = Square(self, (x + y - 1) % 2)
squares.append(squares)
square.setFixedSize(square_size)
grid.addWidget(square, x, y)
self.squares = squares
self.setLayout(grid)
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
# how to resize children?
logging.debug('Resize %s.', self.__class__.__name__)
logging.debug('Size %s.', event.size())
super().resizeEvent(event)
class Square(QWidget):
def __init__(self, parent, color):
super().__init__(parent=parent)
if color:
self.color = QtCore.Qt.white
else:
self.color = QtCore.Qt.black
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
logging.debug('Resize %s.', self.__class__.__name__)
logging.debug('Size %s.', event.size())
super().resizeEvent(event)
def paintEvent(self, event: QPaintEvent) -> None:
painter = QPainter()
painter.begin(self)
painter.fillRect(self.rect(), self.color)
painter.end()
def main():
logging.basicConfig(level=logging.DEBUG)
app = Application(sys.argv)
app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
default_font = QFont()
default_font.setPointSize(12)
app.setFont(default_font)
board = Board()
board.setWindowTitle('Board')
# ugly look
# chessboard.showMaximized()
# looks nize but resize not works
board.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
How should I do resize of square children to avoid holes?
2nd try - improved code but still I have not idea how to resize children
Some new idea with centering it works better (no gaps now) but still I do not know how to resize children (without crash).
After show():
Too wide (it keeps proportions):
Too tall (it keeps proportions):
Larger (it keeps proportions but children is not scaled to free space - I do not know how to resize children still?):
Improved code:
import logging
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QFont, QPaintEvent, QPainter
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QHBoxLayout, QVBoxLayout
class Application(QApplication):
pass
class Board(QWidget):
def square_size(self):
size = self.size()
min_size = min(size.height(), size.width())
min_size_1_8 = min_size // 8
square_size = QSize(min_size_1_8, min_size_1_8)
logging.debug(square_size)
return square_size
def __init__(self, parent=None):
super().__init__(parent=parent)
square_size = self.square_size()
vertical = QVBoxLayout()
horizontal = QHBoxLayout()
grid = QGridLayout()
grid.setSpacing(0)
squares = []
for x in range(8):
for y in range(8):
square = Square(self, (x + y - 1) % 2)
squares.append(squares)
square.setFixedSize(square_size)
grid.addWidget(square, x, y)
self.squares = squares
horizontal.addStretch()
horizontal.addLayout(grid)
horizontal.addStretch()
vertical.addStretch()
vertical.addLayout(horizontal)
vertical.addStretch()
self.setLayout(vertical)
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
# how to resize children?
logging.debug('Resize %s.', self.__class__.__name__)
logging.debug('Size %s.', event.size())
super().resizeEvent(event)
class Square(QWidget):
def __init__(self, parent, color):
super().__init__(parent=parent)
if color:
self.color = QtCore.Qt.white
else:
self.color = QtCore.Qt.black
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
logging.debug('Resize %s.', self.__class__.__name__)
logging.debug('Size %s.', event.size())
super().resizeEvent(event)
def paintEvent(self, event: QPaintEvent) -> None:
painter = QPainter()
painter.begin(self)
painter.fillRect(self.rect(), self.color)
painter.end()
def main():
logging.basicConfig(level=logging.DEBUG)
app = Application(sys.argv)
app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
default_font = QFont()
default_font.setPointSize(12)
app.setFont(default_font)
board = Board()
board.setWindowTitle('Board')
# ugly look
# chessboard.showMaximized()
# looks nice but resize not works
board.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
How should I resize square children without crash?
There are two possible solution.
You can use the Graphics View framework, which is intended exactly for this kind of applications where custom/specific graphics and positioning have to be taken into account, otherwise create a layout subclass.
While reimplementing a layout is slightly simple in this case, you might face some issues as soon as the application becomes more complex. On the other hand, the Graphics View framework has a steep learning curve, as you'll need to understand how it works and how object interaction behaves.
Subclass the layout
Assuming that the square count is always the same, you can reimplement your own layout that will set the correct geometry based on its contents.
In this example I also created a "container" with other widgets to show the resizing in action.
When the window width is very high, it will use the height as a reference and center it horizontally:
On the contrary, when the height is bigger, it will be centered vertically:
Keep in mind that you should not add other widgets to the board, otherwise you'll get into serious issues.
This would not be impossible, but its implementation might be much more complex, as the layout would need to take into account the other widgets positions, size hints and possible expanding directions in order to correctly compute the new geometry.
from PyQt5 import QtCore, QtGui, QtWidgets
class Square(QtWidgets.QWidget):
def __init__(self, parent, color):
super().__init__(parent=parent)
if color:
self.color = QtCore.Qt.white
else:
self.color = QtCore.Qt.black
self.setMinimumSize(50, 50)
def paintEvent(self, event: QtGui.QPaintEvent) -> None:
painter = QtGui.QPainter(self)
painter.fillRect(self.rect(), self.color)
class EvenLayout(QtWidgets.QGridLayout):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setSpacing(0)
def setGeometry(self, oldRect):
# assuming that the minimum size is 50 pixel, find the minimum possible
# "extent" based on the geometry provided
minSize = max(50 * 8, min(oldRect.width(), oldRect.height()))
# create a new squared rectangle based on that size
newRect = QtCore.QRect(0, 0, minSize, minSize)
# move it to the center of the old one
newRect.moveCenter(oldRect.center())
super().setGeometry(newRect)
class Board(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
layout = EvenLayout(self)
self.squares = []
for row in range(8):
for column in range(8):
square = Square(self, not (row + column) & 1)
self.squares.append(square)
layout.addWidget(square, row, column)
class Chess(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QGridLayout(self)
header = QtWidgets.QLabel('Some {}long label'.format('very ' * 20))
layout.addWidget(header, 0, 0, 1, 3, QtCore.Qt.AlignCenter)
self.board = Board()
layout.addWidget(self.board, 1, 1)
leftLayout = QtWidgets.QVBoxLayout()
layout.addLayout(leftLayout, 1, 0)
rightLayout = QtWidgets.QVBoxLayout()
layout.addLayout(rightLayout, 1, 2)
for b in range(1, 9):
leftLayout.addWidget(QtWidgets.QPushButton('Left Btn {}'.format(b)))
rightLayout.addWidget(QtWidgets.QPushButton('Right Btn {}'.format(b)))
footer = QtWidgets.QLabel('Another {}long label'.format('very ' * 18))
layout.addWidget(footer, 2, 0, 1, 3, QtCore.Qt.AlignCenter)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Chess()
w.show()
sys.exit(app.exec_())
Using the Graphics View
The result will be visually identical to the previous one, but while the overall positioning, drawing and interaction would be conceptually a bit easier, understanding how Graphics Views, Scenes and objects work might require you some time to get the hang of it.
from PyQt5 import QtCore, QtGui, QtWidgets
class Square(QtWidgets.QGraphicsWidget):
def __init__(self, color):
super().__init__()
if color:
self.color = QtCore.Qt.white
else:
self.color = QtCore.Qt.black
def paint(self, qp, option, widget):
qp.fillRect(option.rect, self.color)
class Scene(QtWidgets.QGraphicsScene):
def __init__(self):
super().__init__()
self.container = QtWidgets.QGraphicsWidget()
layout = QtWidgets.QGraphicsGridLayout(self.container)
layout.setSpacing(0)
self.container.setContentsMargins(0, 0, 0, 0)
layout.setContentsMargins(0, 0, 0, 0)
self.addItem(self.container)
for row in range(8):
for column in range(8):
square = Square(not (row + column) & 1)
layout.addItem(square, row, column, 1, 1)
class Board(QtWidgets.QGraphicsView):
def __init__(self):
super().__init__()
scene = Scene()
self.setScene(scene)
self.setAlignment(QtCore.Qt.AlignCenter)
# by default a graphics view has a border frame, disable it
self.setFrameShape(0)
# make it transparent
self.setStyleSheet('QGraphicsView {background: transparent;}')
def resizeEvent(self, event):
super().resizeEvent(event)
# zoom the contents keeping the ratio
self.fitInView(self.scene().container, QtCore.Qt.KeepAspectRatio)
class Chess(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QGridLayout(self)
header = QtWidgets.QLabel('Some {}long label'.format('very ' * 20))
layout.addWidget(header, 0, 0, 1, 3, QtCore.Qt.AlignCenter)
self.board = Board()
layout.addWidget(self.board, 1, 1)
leftLayout = QtWidgets.QVBoxLayout()
layout.addLayout(leftLayout, 1, 0)
rightLayout = QtWidgets.QVBoxLayout()
layout.addLayout(rightLayout, 1, 2)
for b in range(1, 9):
leftLayout.addWidget(QtWidgets.QPushButton('Left Btn {}'.format(b)))
rightLayout.addWidget(QtWidgets.QPushButton('Right Btn {}'.format(b)))
footer = QtWidgets.QLabel('Another {}long label'.format('very ' * 18))
layout.addWidget(footer, 2, 0, 1, 3, QtCore.Qt.AlignCenter)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Chess()
w.show()
sys.exit(app.exec_())

Resizing one widget before another

Hi is there a way to resize one widget before another in a layout? For example, when I resize the window, I want one of the widgets to resize to zero first before resizing the other widget.
Here is what I have so far:
from PySide2 import QtCore, QtWidgets, QtGui
class TestWindow(QtWidgets.QMainWindow):
def __init__(self):
super(TestWindow, self).__init__()
wgt = QtWidgets.QWidget(self)
mainLayout = QtWidgets.QHBoxLayout()
wgt.setLayout(mainLayout)
self.setWindowTitle("Test")
l = QtWidgets.QFrame()
r = QtWidgets.QFrame()
l.setStyleSheet("background-color: blue;")
r.setStyleSheet("background-color: green;")
mainLayout.addWidget(l)
mainLayout.addWidget(r)
self.setCentralWidget(wgt)
app = QtWidgets.QApplication()
x = TestWindow()
x.show()
app.exec_()
Here are some pictures showing what I want:
Green disappears first, then blue
So in this example, I want the green box to get smaller first, before the blue one does when I resize the main window. How do I achieve this in QT?
I found a workaround for this. I decided to use a splitter for this solution.
class TitleSplitter(QtWidgets.QSplitter):
def __init__(self):
super(TitleSplitter, self).__init__()
self.setStyleSheet("::handle {background-color: transparent}")
self.setHandleWidth(0)
def resizeEvent(self, event):
""" Restrain the size """
if self.count() > 1:
w = self.widget(0).sizeHint().width()
self.setSizes([w, self.width()-w])
return super(TitleSplitter, self).resizeEvent(event)
def addWidget(self, *args, **kwargs):
""" Hide splitters when widgets added """
super(TitleSplitter, self).addWidget(*args, **kwargs)
self.hideHandles()
def hideHandles(self):
""" Hide our splitters """
for i in range(self.count()):
handle = self.handle(i)
handle.setEnabled(False)
handle.setCursor(QtCore.Qt.ArrowCursor)
handle.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
Usage:
split = TitleSplitter()
l = QtWidgets.QFrame()
r = QtWidgets.QFrame()
l.setStyleSheet("background-color: blue;")
r.setStyleSheet("background-color: green;")
split.addWidget(l)
split.addWidget(r)
It only works if you have 2 widgets added. Ideally I would probably use a layout for this, but this works well enough for me.

how to increase the row height and column width of the tablewidget

I want to add images to cells but it cant show properly,can you please tell me how to increase the row height and column width of the table widget.
Here given bellow is my code:
from PyQt4 import QtGui
import sys
imagePath = "pr.png"
class ImgWidget1(QtGui.QLabel):
def __init__(self, parent=None):
super(ImgWidget1, self).__init__(parent)
pic = QtGui.QPixmap(imagePath)
self.setPixmap(pic)
class ImgWidget2(QtGui.QWidget):
def __init__(self, parent=None):
super(ImgWidget2, self).__init__(parent)
self.pic = QtGui.QPixmap(imagePath)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(0, 0, self.pic)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
tableWidget = QtGui.QTableWidget(10, 2, self)
# tableWidget.horizontalHeader().setStretchLastSection(True)
tableWidget.resizeColumnsToContents()
# tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# tableWidget.setFixedWidth(tableWidget.columnWidth(0) + tableWidget.columnWidth(1))
tableWidget.resize(400,600)
tableWidget.setCellWidget(0, 1, ImgWidget1(self))
tableWidget.setCellWidget(1, 1, ImgWidget2(self))
if __name__ == "__main__":
app = QtGui.QApplication([])
wnd = Widget()
wnd.show()
sys.exit(app.exec_())
When using widgets inside the QTableWidget are not really the content of the table, they are placed on top of it, so resizeColumnsToContents() makes the size of the cells very small since it does not take into account the size of those widgets, resizeColumnsToContents() takes into account the content generated by the QTableWidgetItem.
On the other hand if you want to set the height and width of the cells you must use the headers, in the following example the default size is set using setDefaultSectionSize():
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
tableWidget = QtGui.QTableWidget(10, 2)
vh = tableWidget.verticalHeader()
vh.setDefaultSectionSize(100)
# vh.setResizeMode(QtGui.QHeaderView.Fixed)
hh = tableWidget.horizontalHeader()
hh.setDefaultSectionSize(100)
# hh.setResizeMode(QtGui.QHeaderView.Fixed)
tableWidget.setCellWidget(0, 1, ImgWidget1())
tableWidget.setCellWidget(1, 1, ImgWidget2())
lay = QtGui.QVBoxLayout(self)
lay.addWidget(tableWidget)
If you want the size can not be varied by the user then uncomment the lines.

How do I resize rows with setRowHeight and resizeRowToContents in PyQt4?

I have a small issue with proper resizing of rows in my tableview.
I have a vertical header and no horizontal header.
I tried:
self.Popup.table.setModel(notesTableModel(datainput))
self.Popup.table.horizontalHeader().setVisible(False)
self.Popup.table.verticalHeader().setFixedWidth(200)
for n in xrange(self.Popup.table.model().columnCount()):
self.Popup.table.setColumnWidth(n,150)
And this works fine, but when I try:
for n in xrange(self.Popup.table.model().rowCount()):
self.Popup.table.setRowHeight(n,100)
or
for n in xrange(self.Popup.table.model().rowCount()):
self.Popup.table.resizeRowToContents(n)
No row is resized, even if the text exceeds the length of the cell.
How can I force the rows to fit the data?
For me, both setRowHeight and resizeRowsToContents work as expected. Here's the test script I used:
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self, rows, columns):
super(Window, self).__init__()
self.table = QtGui.QTableView(self)
self.table.horizontalHeader().setVisible(False)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
model = QtGui.QStandardItemModel(rows, columns, self.table)
self.table.setModel(model)
text = 'some long item of text that requires word-wrapping'
for column in range(model.columnCount()):
self.table.setColumnWidth(column, 150)
for row in range(model.rowCount()):
item = QtGui.QStandardItem(text)
model.setItem(row, column, item)
# self.table.setRowHeight(row, 100)
self.table.resizeRowsToContents()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window(4, 3)
window.setGeometry(800, 150, 500, 250)
window.show()
sys.exit(app.exec_())
And here's what it looks like:

Categories