How to align the text to center of cells in a QTableWidget

大兔子大兔子 提交于 2019-12-02 04:20:30

问题


I am using PyQt based on Qt4. My Editor is PyCharm 2017.3 and my python version is 3.4. I am scraping some text from a website. I am trying to align that text to the center of the cell in a QTableWidget.

item = QTableWidgetItem(scraped_age).setTextAlignment(Qt.AlignHCenter)
self.tableWidget.setItem(x, 2,item)

Therefore while putting the item in the cell, I am trying to align it as per the documentation. The problem is that the data is not showing up.


It did show up when I removed setTextAlignment method as shown below

item = QTableWidgetItem(scraped_age)
self.tableWidget.setItem(x, 2,item)


回答1:


This line of code:

item = QTableWidgetItem(scraped_age).setTextAlignment(Qt.AlignHCenter)

will not work properly, because it throws away the item it creates before assigning it to the variable. The variable will in fact be set to None, which is the return value of setTextAlignment(). Instead, you must do this:

item = QTableWidgetItem(scraped_age) # create the item
item.setTextAlignment(Qt.AlignHCenter) # change the alignment


来源:https://stackoverflow.com/questions/47971275/how-to-align-the-text-to-center-of-cells-in-a-qtablewidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!