logo
down
shadow

Pyqt QTablewidget wordwrap lines


Pyqt QTablewidget wordwrap lines

By : Do8fe7aevol4lopo
Date : November 21 2020, 04:01 AM
wish help you to fix your issue You have to enable the wordwrap in the QTextDocument in addition to setting the sectionResizeMode of the vertical header to QHeaderView::ResizeToContents:
code :
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class HighlightDelegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None):
        super(HighlightDelegate, self).__init__(parent)
        self._filters = []
        self._wordwrap = False
        self.doc = QtGui.QTextDocument(self)

    def paint(self, painter, option, index):
        painter.save()
        options = QtWidgets.QStyleOptionViewItem(option)
        self.initStyleOption(options, index)
        self.doc.setPlainText(options.text)
        self.apply_highlight()

        if self._wordwrap:
            self.doc.setTextWidth(options.rect.width())
        options.text = ""

        style = QApplication.style() if options.widget is None else options.widget.style()
        style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)

        if self._wordwrap:
            painter.translate(options.rect.left(), options.rect.top())
            clip = QtCore.QRectF(QtCore.QPointF(), QtCore.QSizeF(options.rect.size()))
            self.doc.drawContents(painter, clip)
        else:
            ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
            if option.state & QtWidgets.QStyle.State_Selected:
                ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
                    QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
            else:
                ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
                    QtGui.QPalette.Active, QtGui.QPalette.Text))
            textRect = style.subElementRect(QtWidgets.QStyle.SE_ItemViewItemText, options, None)
            if index.column() != 0:
                textRect.adjust(5, 0, 0, 0)
            constant = 4
            margin = (option.rect.height() - options.fontMetrics.height()) // 2
            margin = margin - constant
            textRect.setTop(textRect.top() + margin)
            painter.translate(textRect.topLeft())
            painter.setClipRect(textRect.translated(-textRect.topLeft()))
            self.doc.documentLayout().draw(painter, ctx)

        painter.restore()
        s = QtCore.QSize(self.doc.idealWidth(), self.doc.size().height())
        index.model().setData(index, s, QtCore.Qt.SizeHintRole)

    def apply_highlight(self):
        cursor = QtGui.QTextCursor(self.doc)
        cursor.beginEditBlock()
        fmt = QtGui.QTextCharFormat()
        fmt.setForeground(QtCore.Qt.red)
        for f in self.filters():
            highlightCursor = QtGui.QTextCursor(self.doc)
            while not highlightCursor.isNull() and not highlightCursor.atEnd():
                highlightCursor = self.doc.find(f, highlightCursor)
                if not highlightCursor.isNull():
                    highlightCursor.mergeCharFormat(fmt)
        cursor.endEditBlock()

    @QtCore.pyqtSlot(list)
    def setFilters(self, filters):
        if self._filters == filters: return
        self._filters = filters
        self.parent().viewport().update()

    def filters(self):
        return self._filters

    def setWordWrap(self, on):
        self._wordwrap = on
        mode = QtGui.QTextOption.WordWrap if on else QtGui.QTextOption.WrapAtWordBoundaryOrAnywhere

        textOption = QtGui.QTextOption(self.doc.defaultTextOption())
        textOption.setWrapMode(mode)
        self.doc.setDefaultTextOption(textOption)
        self.parent().viewport().update()

data_single = {'Position':['hallo i like to do this and it would be nice if there was a new line. othere lines and so one.','b'], 'LV-Text': ['c','d'], 'Fundwörter': ['e','f'], 'Hersteller': ['g','h']}
words_in_columns = ['a','b']

class main_result_pos(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(main_result_pos, self).__init__(parent)
        self.table = QtWidgets.QTableWidget(100, 6)
        self.table.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
        self.table.setSortingEnabled(True)

        self._delegate = HighlightDelegate(self.table)
        self.table.setItemDelegate(self._delegate)
        le = QtWidgets.QLineEdit(textChanged=self.on_textChanged)

        search_list = [word for column in words_in_columns for word in column]
        list_c_str = ' '.join(search_list)
        le.setText(list_c_str)

        horHeaders = []
        for col, key in enumerate(sorted(data_single.keys())):
            horHeaders.append(key)
            for row, item in enumerate(data_single[key]):
                newitem = QtWidgets.QTableWidgetItem(item)
                self.table.setItem(row, col, newitem)
        self.table.setHorizontalHeaderLabels(horHeaders)

        self._delegate.setWordWrap(True)
        self.resize(640, 480)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(le)
        lay.addWidget(self.table)

    @QtCore.pyqtSlot(str)
    def on_textChanged(self, text):
        self._delegate.setFilters(list(set(text.split())))

def main():
    app = QtWidgets.QApplication(sys.argv)
    ex = main_result_pos()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


Share : facebook icon twitter icon
PyQt: QTableWidget to .xls file

PyQt: QTableWidget to .xls file


By : Neeraj
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You might also find it more concise and easier to use the output of the range (or xrange) as the indexes for your tableWidget.item call rather than worrying about incrementing your own counters. You might be using the sheet itself in other places in code, but if you're not, it would save you some memory to not assign the sheet to be an attribute variable of your class:
code :
def savefile(self):
    filename = unicode(QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)"))    
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
    self.add2(sheet)
    wbk.save(filename)

def add2(self, sheet):
    for currentColumn in range(self.tableWidget.columnCount()):
        for currentRow in range(self.tableWidget.rowCount()):
            try:
                teext = str(self.tableWidget.item(currentRow, currentColumn).text()
                sheet.write(currentRow, currentColumn, teext)
            except AttributeError:
                pass
PyQt : Checkbox in QTableWidget

PyQt : Checkbox in QTableWidget


By : Youxun Yu
Date : March 29 2020, 07:55 AM
hope this fix your issue I use following code to put a checkbox in the 9th column of my QTableWidget , One way to do it would be:
code :
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns):
            for row in range(rows):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                if row % 2:
                    item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                                  QtCore.Qt.ItemIsEnabled)
                    item.setCheckState(QtCore.Qt.Unchecked)
                self.table.setItem(row, column, item)
        self.table.itemClicked.connect(self.handleItemClicked)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            print('"%s" Checked' % item.text())
            self._list.append(item.row())
            print(self._list)
        else:
            print('"%s" Clicked' % item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(6, 3)
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())
How can I get the selected row's value of a qtablewidget in PyQt?

How can I get the selected row's value of a qtablewidget in PyQt?


By : Patrick Matias Araúj
Date : March 29 2020, 07:55 AM
Hope this helps I am working on a small library application. I am getting data from an excel sheet. And then sent to qtablewidget. , I solved myself. Here is the solution:
code :
liste = []
    for i in range(34):
        liste.append(self.ui.tableWidget.item(self.ui.tableWidget.currentRow(), i).text())

    print(liste)
Implementing a delegate for wordwrap in a QTreeView (Qt/PySide/PyQt)?

Implementing a delegate for wordwrap in a QTreeView (Qt/PySide/PyQt)?


By : SgtBipul
Date : March 29 2020, 07:55 AM
it fixes the issue The issue seems to stem from the fact that the value for option.rect.width() passed into QStyledItemDelegate.sizeHint() is -1. This is obviously bogus!
I've solved this by storing the width in the model from within the paint() method and accessing this from sizeHint().
code :
index.model().setData(index, option.rect.width(), QtCore.Qt.UserRole+1)
width = index.model().data(index, QtCore.Qt.UserRole+1)
if not width:
    width = 20
document.setTextWidth(width)
How do I add a layout to a Qtablewidget in pyqt?

How do I add a layout to a Qtablewidget in pyqt?


By : Tiến Phan Ngọc
Date : March 29 2020, 07:55 AM
Any of those help add {your table}.table.horizontalHeader().setStretchLastSection(True) and/or {your table}.verticalHeader().setStretchLastSection(True)
code :
import sys

from PyQt4 import QtGui
from PyQt4 import QtCore


class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent=parent)
        QtGui.QTableWidget.setMinimumSize(self, 500, 500)
        QtGui.QTableWidget.setWindowTitle(self, "Custom table widget")
        self.table = QtGui.QTableWidget()
        rowf = 3
        self.table.setColumnCount(3)
        self.table.setRowCount(rowf)
        self.table.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("col1"))
        self.table.setHorizontalHeaderItem(1, QtGui.QTableWidgetItem("col2"))
        self.table.setHorizontalHeaderItem(2, QtGui.QTableWidgetItem("col3"))
        self.table.horizontalHeader().setStretchLastSection(True)
        # self.table.verticalHeader().setStretchLastSection(True)

        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok)

        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.table)
        self.verticalLayout.addWidget(self.buttonBox)

        self.buttonBox.accepted.connect(self.close)
        self.buttonBox.rejected.connect(self.close)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())
Related Posts Related Posts :
  • Creating a Dataframe of Proportions
  • Scrapy with dynamic captcha
  • In python, how do I get urllib to recognize multiple lines in a string as separate URLs?
  • Add prefix and suffix to each element of a nested list
  • Generate string set from csv file in Python
  • Custom usage message for many-valued argument
  • Python Class, how to skip a wrong entry and proceed to next entry
  • Numpy efficient way to parse array of string
  • Kivy , Python: Update Label on_file_drop
  • What does it mean if a deeper conv layer converges first?
  • Selecting User in client.send_message() from arg list
  • python slicing multi levels list of dict using list comprehension
  • Value Error problem with multicell Dimensions must be equal, but are 20 and 13
  • How to print a board with coordinates?
  • Keras LSTM shape doesn't contain length of sequence
  • Boxplot with Pandas in Python
  • How can I rename a PySpark dataframe column by index? (handle duplicated column names)
  • How to calculate hash of a python class object
  • Using ideas from HashEmbeddings with sklearn's HashingVectorizer
  • keycloak.exceptions.KeycloakGetError: 404: b'' using Python 3.7
  • How to modify a column in a SQLite3?
  • VS Integration Services: flat file source to OLE DB destination - detect new data columns in file, add columns to table,
  • Customize xticks in matplotlib plot
  • How can I show the image in a labelframe which is inserted through askopenfilename?
  • Boxplot with distibution size histogram on top (and median regression)
  • Fit differential equation with scipy
  • ModuleNotFoundError: Correct setup
  • How to pass rendered plot to a html file through render_template?
  • Create flat ndarray from DataFrame column containing arrays
  • Bring radial axes labels in front of lines of polar plot matplotlib
  • Python3: Unable to split word from parsed data
  • Using Python to login to a website and web scrape
  • Customise shift in matplotlib offset
  • Combining and Reshaping rows and columns of 2 dataframes in R or Python
  • Regex condition after and before a known phrase
  • subplots based on records of two different pandas DataFrames ( with same structure) using Seaborn or Matplotlib
  • find numpy array in other numpy array
  • Print Triangle Pyramid pattern using for loop python
  • Python Script Running through Command Line Not Creating CSV
  • Questions about Subclassing
  • Creating list with dictionary instead of multiple dictionaries in python
  • Sorting queryset results in a template
  • Django Rest Framework allow not authenticated access to a view in certain cases
  • How do I efficiently map integers to URIs in a multidemnsional array?
  • Installing Python packages for Visual Studio Code
  • How to merge two columns into one in pandas dataframe
  • Decompose string of different symbols in python
  • pandas merge and group concat
  • How to traverse tree for making binary code from a HuffmanTree?
  • Check if IP is in network on Python3
  • non equally spaced points along x-axis in a plot
  • Concatenation of text files consisting list of lists?
  • Use regex to parse characters on a line of text
  • pandas df.fillna - filling NaNs after outer join with correct values
  • How can I undo a time series conversion of a pandas dataframe?
  • Virtual environment is not working in Django
  • FileNotFoundError in Python during Arabic text analysis
  • How to read email using python and smtplib
  • How to write a function which takes a string and turns into a single digit?
  • Linear Regression without Least Squares in sklearn
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org