本文整理汇总了Python中PyQt5.QtWidgets.QTableWidget.cellWidget方法的典型用法代码示例。如果您正苦于以下问题:Python QTableWidget.cellWidget方法的具体用法?Python QTableWidget.cellWidget怎么用?Python QTableWidget.cellWidget使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableWidget
的用法示例。
在下文中一共展示了QTableWidget.cellWidget方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RowControlTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import cellWidget [as 别名]
class RowControlTableWidget(QWidget):
def __init__(self, items = [('col1_name', 'default text'), ('col2_name', ['dfeault', 'combo', 'elements'])]):
super(RowControlTableWidget, self).__init__()
self.ordered_column_keys = [ z[0] for z in items ]
self.default_row = { z[0]:z[1] for z in items }
self.table = QTableWidget(1, len(items))
self.table.setHorizontalHeaderLabels(self.ordered_column_keys)
self.add_row_button = QPushButton('Add Row')
self.add_row_button.clicked.connect(self.add_row)
self.delete_row_button = QPushButton('Delete Row')
self.delete_row_button.clicked.connect(self.delete_row)
hbox = QHBoxLayout()
hbox.setContentsMargins(0,0,0,0)
hbox.addWidget(self.add_row_button)
hbox.addWidget(self.delete_row_button)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.layout.addLayout(hbox)
self.layout.addWidget(self.table)
def reset_row_template(self, items = [('col1_name', 'default text'), ('col2_name', ['dfeault', 'combo', 'elements'])]):
# use to (re)set the values of the drop down elements inside the table cells
self.ordered_column_keys = [ z[0] for z in items ]
self.default_row = { z[0]:z[1] for z in items }
def add_row(self):
new_row_number = self.table.rowCount()
self.table.setRowCount(self.table.rowCount()+1)
for column, key in enumerate(self.ordered_column_keys):
value = self.default_row[key]
# print(value, type(value))
if isinstance(value, str):
item = QTableWidgetItem(value)
self.table.setItem(new_row_number, column, item)
elif isinstance(value, list):
combo_box = QComboBox()
combo_box.insertItems(0, value)
# combo_box.setCurrentText(value[0])
self.table.setCellWidget(new_row_number, column, combo_box)
else:
message = 'Table cells are expected to be either Dict (added asQComboBox via setCellWidget) or String (added as QTableWidgetItem). You have type ' + str(type(value))
message += ' at position ' + str(new_row_number) + ', ' + str(column)
raise CellObjectException(message)
def delete_row(self):
self.table.removeRow(self.table.currentRow())
def show(self):
self.table.show()
self.add_row_button.show()
self.delete_row_button.show()
def hide(self):
self.table.hide()
self.add_row_button.hide()
self.delete_row_button.hide()
def set_text(self, items):
# where items should be list of lists of objects that can be either dict (loads as QComboBox) or string (used in setItem)
# print('siphon itmes', items)
self.table.setRowCount(len(items))
self.table.setColumnCount(len(items[0]))
for i, row in enumerate(items):
# print('siphon row', row)
for j, value in enumerate(row):
if isinstance(value, str):
item = QTableWidgetItem(value)
self.table.setItem(i, j, item)
elif isinstance(value, dict):
combo_box = QComboBox()
dict_keys = list(value.keys())
selected = dict_keys[0]
if isinstance(value[selected], dict):
combo_box.insertItems(0, list(value[selected].values()))
else:
combo_box.insertItems(0, value[selected])
combo_box.setCurrentText(selected)
self.table.setCellWidget(i, j, combo_box)
else:
message = 'Table cells are expected to be either Dict (added asQComboBox via setCellWidget) or String (added as QTableWidgetItem). You have type ' + str(type(value))
message += ' at position ' + str(i) + ', ' + str(j)
raise CellObjectException(message)
def get_values(self):
table = []
for i in range(self.table.rowCount()):
row = []
for j in range(self.table.columnCount()):
try:
row.append(self.table.item(i, j).text())
except AttributeError:
row.append(self.table.cellWidget(i, j).currentText())
table.append(row)
return table
示例2: InputTableModel
# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import cellWidget [as 别名]
class InputTableModel(QDialog):
def __init__(self, title, numVar, numCons, typeVar, objCrit, parent=None):
super(InputTableModel, self).__init__(parent)
self.problem = None
self.problemTitle = title
self.numVariables = numVar
self.numConstraints = numCons
self.objCriterion = objCrit
self.typeVariable = typeVar
self.tableModel = QTableWidget(self.numConstraints+1, self.numVariables+2)
self.tableModel.setItemDelegate(Delegate(self))
listVariables = []
for m in range(self.numVariables):
listVariables.append("X"+str(m))
listVariables.extend(["Direction","R.H.S"])
#Generar Filas
listConstraints = ["Objetive"]
for m in range(self.numConstraints):
listConstraints.append("C"+str(m))
combo = QComboBox()
combo.addItem('<')
combo.addItem('<=')
combo.addItem('=')
combo.addItem('>=')
combo.addItem('>')
self.tableModel.setCellWidget(m+1, self.numVariables, combo)
#listConstraints.extend(["LowerBound","UpperBound", "VariableType"])
self.tableModel.setCellWidget(0, self.numVariables, QLabel(""))
self.tableModel.setHorizontalHeaderLabels(listVariables)
self.tableModel.setVerticalHeaderLabels(listConstraints)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.verify)
buttonBox.rejected.connect(self.reject)
f = "Problem Title: "
if self.objCriterion == True:
f = f + self.problemTitle + " - Objetive: Maximitation"
else:
f = f + self.problemTitle + " - Objetive: Minimization"
t = QLabel(f)
mainLayout = QVBoxLayout()
mainLayout.addWidget(t)
mainLayout.addWidget(self.tableModel)
mainLayout.addWidget(buttonBox)
width = self.tableModel.columnWidth(1)*(self.tableModel.columnCount()+1)
height = self.tableModel.rowHeight(0)*(self.tableModel.rowCount()+4)
self.resize(QSize(width, height))
self.setWindowTitle("Input Problem Model")
self.setLayout(mainLayout)
def verify(self):
#Matix Values
matrix = []
matrixGraph = []
for f in range(self.tableModel.rowCount()):
row = []
for c in range(self.tableModel.columnCount()):
if c == self.numVariables:
item = self.tableModel.cellWidget(f,c)
if type(item) == QComboBox:
row.append(item.currentText())
else:
item = self.tableModel.item(f,c)
if item == None:
row.append(0)
else:
row.append(float(item.text()))
if f == 0:
row.pop(-1)
matrix.append(row)
flag = False
for s in range(len(matrix[0])):
if matrix[0][s] == 0:
flag = True
if flag == False:
#Title and Criterion
if self.objCriterion:
self.problem = LpProblem(self.problemTitle, LpMaximize)
else:
self.problem = LpProblem(self.problemTitle, LpMinimize)
#Non Negative Continuous
if self.typeVariable == 1:
x = LpVariable.matrix("x", list(range(self.numVariables)), 0, None)
print "Non Negative Continuous"
#Non Negative Integer
elif self.typeVariable == 2:
x = LpVariable.matrix("x", list(range(self.numVariables)), 0, None
, LpInteger)
#.........这里部分代码省略.........
示例3: Menumaker
# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import cellWidget [as 别名]
class Menumaker(QWidget):
entries = []
def __init__(self):
super().__init__()
self.initTable()
gen = QPushButton('Generate')
gen.clicked.connect(self.output)
filename = QLineEdit(FILENAME)
hbox0 = QHBoxLayout()
hbox0.addWidget(gen)
hbox0.addWidget(filename)
save = QPushButton('Save')
savefn = QLineEdit('TileMenuDesktopEntries.cfg')
hbox1 = QHBoxLayout()
hbox1.addWidget(save)
hbox1.addWidget(savefn)
load = QPushButton('Load')
loadfn = QLineEdit('TileMenuDesktopEntries.cfg')
hbox2 = QHBoxLayout()
hbox2.addWidget(load)
hbox2.addWidget(loadfn)
vbox = QVBoxLayout()
vbox.addWidget(self.table)
vbox.addLayout(hbox1)
vbox.addLayout(hbox2)
vbox.addLayout(hbox0)
self.setGeometry(300, 300, 960, 500)
self.setLayout(vbox)
self.show()
def findEntries(self):
desktopfiles = []
for i in APPPATHLIST:
try:
lst = os.listdir(path=i)
for j in lst:
desktopfiles.append(i + '/' + j)
except FileNotFoundError:
pass
self.entries = []
i = 0
for f in desktopfiles:
file = open(f)
params = {}
for line in file:
s = line.split('=')
if s[0] == 'Icon' or s[0] == 'Exec' or s[0] == 'Name':
params.update({s[0] : s[1][0:-1]})
if params.get('Icon', None) == None:
params['Icon'] = 'noicon'
if params.get('Name', None) == None:
params['Name'] = 'noname'
if params.get('Exec', None) == None:
params['Exec'] = 'true'
params['On'] = CHECKALL
s = SIZE
x = i % W * s
y = i // W * s
params.update({'Size':s, 'x':x, 'y':y})
params['Icon'] = self.iconPath(params['Icon'])
self.entries.append(params)
i += 1
def output(self, filename):
self.getEntriesFromTable()
filename = 'test.py'
out = open(filename, 'w')
out.write(BEGIN)
for e in self.entries:
if e.get('Exec') != None and e.get('On'):
out.write(TEMPLATE % (e['x'], e['y'], e['Size'], e.get('Exec', ''), e.get('Icon', '')))
out.close()
def initTable(self):
self.findEntries()
self.table = QTableWidget(len(self.entries), 4)
self.table.setColumnWidth(0, self.table.rowHeight(0))
self.table.setColumnWidth(1, 150)
self.table.setColumnWidth(2, 300)
self.table.setColumnWidth(3, 400)
i = 0
for e in self.entries:
self.table.setCellWidget(i, 0, QCheckBox(''))
self.table.cellWidget(i, 0).setCheckState(e['On'])
self.table.cellWidget(i, 0).setTristate(False)
self.table.setCellWidget(i, 1, QLabel(e['Name']))
self.table.setCellWidget(i, 2, QLineEdit(e['Exec']))
self.table.setCellWidget(i, 3, QLineEdit(e['Icon']))
i += 1
def getEntriesFromTable(self):
for i in range(self.table.rowCount()):
self.entries[i]['On'] = bool(self.table.cellWidget(i, 0).checkState())
self.entries[i]['Exec'] = self.table.cellWidget(i, 2).text()
self.entries[i]['Icon'] = self.table.cellWidget(i, 3).text()
示例4: addTileDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTableWidget import cellWidget [as 别名]
class addTileDialog(QDialog):
output = None
ready = False
def __init__(self):
super().__init__()
self.tilename = QComboBox()
for tile in tilelist.tilelist:
self.tilename.addItem(tile.__name__, tile)
self.tilename.currentIndexChanged.connect(self.setTable)
okbtn = QPushButton('Ok')
okbtn.clicked.connect(self.onOk)
clbtn = QPushButton('Cancel')
clbtn.clicked.connect(self.onCancel)
self.table = QTableWidget(2, 2)
self.setTable(self.tilename.currentIndex())
hbox = QHBoxLayout()
hbox.addWidget(clbtn)
hbox.addWidget(okbtn)
vbox = QVBoxLayout()
vbox.addWidget(self.tilename)
vbox.addWidget(self.table)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.resize(400, 300)
self.table.setColumnWidth(1, 250)
self.setModal(True)
self.show()
def setTable(self, index):
try:
raw = 2 + len(self.tilename.itemData(index).extraText)
except TypeError:
raw = 2
self.table.setRowCount(raw)
self.table.setItem(0, 0, QTableWidgetItem('X position'))
self.table.setCellWidget(0, 1, QSpinBox())
self.table.setItem(1, 0, QTableWidgetItem('Y position'))
self.table.setCellWidget(1, 1, QSpinBox())
if self.tilename.itemData(index).extraText != None:
i = 0
for line in self.tilename.itemData(index).extraText:
self.table.setItem(2 + i, 0, QTableWidgetItem(line))
self.table.setCellWidget(2 + i, 1, QLineEdit(''))
i += 1
def getParams(self):
x = self.table.cellWidget(0, 1).value()
y = self.table.cellWidget(1, 1).value()
extra = None
if self.tilename.currentData().extraTypes != None:
i = 0
extra = []
for t in self.tilename.currentData().extraTypes:
if t == 'bool':
extra.append(bool(self.table.cellWidget(2 + i, 1).text()))
elif t == 'int':
extra.append(int(self.table.cellWidget(2 + i, 1).text()))
elif t == 'float':
extra.append(float(self.table.cellWidget(2 + i, 1).text()))
elif t == 'str':
extra.append(str(self.table.cellWidget(2 + i, 1).text()))
else:
extra.append(str(self.table.cellWidget(2 + i, 1).text()))
i += 1
return (x, y, extra)
def getTileParams(self):
return self.output
def onOk(self):
self.output = (self.tilename.currentData(), self.getParams())
self.ready = True
self.accept()
def onCancel(self):
self.output = (self.tilename.currentData(), self.getParams())
self.ready = True
self.reject()