Issue
Within a task I want to read in an Excel document and display it with a PyQt5 GUI. As indicator I wanted to use the QTabelWidget. However, the Excel table has long strings, which are to be displayed using line wrap. Unfortunately, so far I haven't found a way to enable a line wrap on a QTabelWidget. Is such a thing possible at all? So far I have read that there is probably a way using the QTextDocument class. However, this has not worked for me yet either.
Below you will find a minimal example in which simply two constant strings are to be displayed in the widget.
import PyQt5.QtWidgets as qtw
import PyQt5.QtCore as qtc
import PyQt5.QtGui as qtg
class MainWindow(qtw.QMainWindow):
def __init__(self):
super().__init__()
self.window_width, self.window_height = 300, 200
self.resize(self.window_width, self.window_height)
layout = qtw.QVBoxLayout()
self.setLayout(layout)
self.table = qtw.QTableWidget()
layout.addWidget(self.table)
self.button = qtw.QPushButton('&Load Data')
layout.addWidget(self.button)
widget = qtw.QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.button.clicked.connect(self.Set)
self.show()
def Set(self):
string0 = 'These is String zero'
string1 = 'This is a super long text that should be displayed using line breaks. This is a super long text that should be displayed using line breaks.'
self.table.setRowCount(2)
self.table.setColumnCount(2)
self.table.setHorizontalHeaderLabels(['String1', 'String2'])
self.table.setItem(0,0, qtw.QTableWidgetItem(string0))
self.table.setItem(0,1, qtw.QTableWidgetItem(string1))
if __name__== '__main__':
import sys
app = qtw.QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
The ouput looks like this: Output
Hope someone can help & Thanks.
Solution
Line wraps are enabled by default, QTableWidget
displays elided text when cell doesn't have enough space to show all the text, if you resize cell vertically (by resizing the row) you'll get multiline text.
You can change row heights using self.table.verticalHeader().setDefaultSectionSize(100)
or height of specific row using self.table.setRowHeight(0, 100)
or adjust heights using self.table.resizeRowsToContents()
after setItem
.
Answered By - mugiseyebrows
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.