pyqt QTablewidget remove scrollbar to show full ta

2020-02-29 00:01发布

问题:

I have a scrollview to which I dynamically add QTableWidgets. However, the QTables themselves also have scrollbars and therefore dont show the full table. Is there a way to disable the scroll bar so that the table always gets shown in full?

EDIT: I added

    self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

as suggested. The scroll bar does disappear, but it still only shows the partial tables (Ican scroll with hovering iverthe table and using the mouse wheel, still). The code for the Widget is below

from PySide.QtGui import *
from PySide.QtCore import *

class MdTable(QTableWidget):
    def __init__(self, data, depth, *args):

        QTableWidget.__init__(self, *args)
        self.hheaders = ["c1", "c2", "c3", "c4"]
        self.depth = depth
        self.bids = data
        self.setData()

    def setData(self):

        self.setRowCount(self.depth)
        self.setColumnCount(5)

        for i in xrange(self.depth):
            if len(self.data) > i:
                d1= QTableWidgetItem(str(self.data[i][0]))
                d2= QTableWidgetItem(str(self.data[i][1]))
                self.setItem(i, 1, d1)
                self.setItem(i, 2, d2)

        self.setHorizontalHeaderLabels(self.hheaders)
        self.verticalHeader().setVisible(False)
        self.resizeRowsToContents()
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

回答1:

If you just want to delete the Scrollbar you must use:

{QtableWidget}.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
{QtableWidget}.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

If you want to show the expanded QTableWidget, add this to the end of the setData() method:

self.setMaximumSize(self.getQTableWidgetSize())
self.setMinimumSize(self.getQTableWidgetSize())

and define getQTableWidgetSize(self) like this:

def getQTableWidgetSize(self):
    w = self.verticalHeader().width() + 4  # +4 seems to be needed
    for i in range(self.columnCount()):
        w += self.columnWidth(i)  # seems to include gridline (on my machine)
    h = self.horizontalHeader().height() + 4
    for i in range(self.rowCount()):
        h += self.rowHeight(i)
    return QtCore.QSize(w, h)

Note: The function getQTableWidgetSize is a conversion of the code in C ++ to python of the following post: How to determine the correct size of a QTableWidget?