I am trying to put a QtableWidget inside a QScrollArea (only one widget) to be able to scroll it vertically and horizontaly (I have reasons not to use scrollbars in Qtablewidget ). However, no scrollbar appears even though the tableWidget can’t fit inside the window so I set QtCore.Qt.ScrollBarAlwaysOn, and now they are there but they are gray and still I can't scroll.

Here is my code:

class Table(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)
        layout = QtGui.QGridLayout() 
        tableWidget = QtGui.QTableWidget()
        #.... set up and populate tableWidget here 1000rows-10col ....
        myScrollArea = QtGui.QScrollArea()
        myScrollArea.setWidgetResizable(True)
        myScrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        myScrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        myScrollArea.setWidget(tableWidget)
        layout.addWidget(myScrollArea)
        self.setLayout(layout)
        self.setMinimumSize(1000, 700)

I am begginer with PyQt and I don't really understand layouts and containers, so I can't figure out what I'm doing wrong. Please point me in right direction, help would be appreciated.

有帮助吗?

解决方案 2

I finally get it: I've used resizeColumnsToContents() and resizeRowsToContents() to make the columns/rows of the table adjust to the data - text, but that doesn't do the same thing with the Table itself - table height and width stays the same. So in order to make table to be sized around the rows and columns I've used this:

self.table.resizeRowsToContents()
self.table.resizeColumnsToContents()   
self.table.setFixedSize(self.table.horizontalHeader().length(), self.table.verticalHeader().length())

and now I can scroll with QScrollArea's scrollbars through entire table.

其他提示

QtScrollBar by default has horizontal and vertical scrollBar. tablewidget by default has horizontal and vertical scrollBar. so i have made it off. just using the resize event i have resized width and height of tablewidget.

class MainWin(QtGui.QDialog):
def __init__(self,parent=None):
    QtGui.QDialog.__init__(self,parent)

    self.table =QtGui.QTableWidget(100,4)
    self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    self.table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

    lay = QtGui.QGridLayout()
    self.sc = QtGui.QScrollArea()
    self.sc.setWidget(self.table)
    lay.addWidget(self.sc,0,0)
    self.setLayout(lay)


def resizeEvent(self,event):
    self.table.resize(self.sc.width(),self.sc.height())




def main():
    app=QtGui.QApplication(sys.argv)
    win=MainWin()
    win.show()
    sys.exit(app.exec_())

main()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top