[英]How can i align a CellWidget of a TableWidget to the center of the Item in pyqt5
我在 tableWidget 中有一個 comboBox,verticalHeader DefaultSectionSize 為 60。
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self,parent)
self.table = QTableWidget()
self.setCentralWidget(self.table)
self.table.verticalHeader().setDefaultSectionSize(60)
self.table.setColumnCount(2)
self.table.setRowCount(2)
data = ["1","2"]
for i in range(2):
item = QTableWidgetItem(data[i])
self.table.setItem(i,0,item)
self.combo_sell = QComboBox()
self.combo_sell.setMaximumHeight(30)
self.table.setCellWidget(i,1,self.combo_sell)
但由於我將 comboBox 的最大尺寸設置為 30,它停留在項目的頂部。
我想知道是否有辦法將其與中心對齊。
設置索引小部件時,視圖會嘗試根據索引的visualRect()
設置小部件幾何形狀。 設置固定尺寸會強制小部件將自身與默認原點對齊,默認原點通常是左上角。
將具有固定高度的小部件垂直居中的唯一方法是使用具有垂直框布局的容器並將組合添加到其中:
for i in range(2):
item = QTableWidgetItem(data[i])
item.setTextAlignment(Qt.AlignCenter)
self.table.setItem(i,0,item)
container = QWidget()
layout = QVBoxLayout(container)
combo_sell = QComboBox()
layout.addWidget(combo_sell)
combo_sell.setMaximumHeight(30)
self.table.setCellWidget(i, 1, container)
注意:在 for 循環中設置實例屬性是沒有意義的,因為每次循環循環都會丟失引用。
如果您需要對組合的簡單引用,可以將其設置為小部件的屬性:
container.combo_sell = QComboBox()
通過這種方式,您可以在需要時輕松訪問它:
widget = self.table.cellWidget(row, column)
if widget and hasattr(widget, 'combo'):
combo = widget.combo
print(combo.currentIndex())
請注意,該引用是為小部件的 python 包裝器創建的,並且該行為可能會在 Qt 的未來版本中發生變化。 實現這一點的更好和更安全的方法是使用子類,這也將允許更輕松地訪問組合:
class TableCombo(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout(self)
self.combo = QComboBox()
layout.addWidget(self.combo)
self.combo.setMaximumHeight(30)
self.currentIndex = self.combo.currentIndex
self.setCurrentIndex = self.combo.setCurrentIndex
self.addItems = self.combo.addItems
# ...
combo_sell = TableCombo()
self.table.setCellWidget(i, 1, combo_sell)
# ...
combo = self.table.cellWidget(row, column)
print(combo.currentIndex())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.