本文整理汇总了Python中PyQt5.QtWidgets.QTableView.setColumnWidth方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.setColumnWidth方法的具体用法?Python QTableView.setColumnWidth怎么用?Python QTableView.setColumnWidth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableView
的用法示例。
在下文中一共展示了QTableView.setColumnWidth方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
#.........这里部分代码省略.........
self.model2.setHeaderData(1, Qt.Horizontal, "개수")
def setupViews(self):
splitter = QSplitter()
self.table = QTableView()
self.pieChart = PieView()
splitter.addWidget(self.pieChart)
splitter.addWidget(self.table)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 0)
self.table.setModel(self.model)
self.pieChart.setModel(self.model2)
self.selectionModel = QItemSelectionModel(self.model2)
self.table.setSelectionModel(self.selectionModel)
#self.pieChart.setSelectionModel(self.selectionModel)
#table.setColumnWidth(0,100)
self.setCentralWidget(splitter)
self.table.doubleClicked.connect(self.ClickAction_table)
def readDB(self):
con = sqlite3.connect("mystudy.db")
cur = con.cursor()
cur.execute("select subject, readcheck from study;")
self.model.removeRows(0, self.model.rowCount(QModelIndex()),
QModelIndex())
self.model2.removeRows(0, self.model2.rowCount(QModelIndex()),
QModelIndex())
row = 0
for line in cur:
if line[1] ==1:
result = "○"
else:
result = "X"
self.model.insertRows(row, 1, QModelIndex())
self.model.setData(self.model.index(row, 0, QModelIndex()), line[0])
self.model.setData(self.model.index(row, 1, QModelIndex()),result)
self.model.setData(self.model.index(row, 1, QModelIndex()), QVariant(Qt.AlignCenter),Qt.TextAlignmentRole)
row += 1
cur.execute("select count() from study ;")
for line in cur:
self.studyTotal =line[0]
cur.execute("select count() from study where readcheck=1;")
for line in cur:
self.studyRead =line[0]
#print("총 개수 " ,self.studyTotal ," 학습한개수", self.studyRead )
con.close()
row=0
self.model2.insertRows(row, 1, QModelIndex())
self.model2.setData(self.model2.index(row, 0, QModelIndex()),"학습")
self.model2.setData(self.model2.index(row, 1, QModelIndex()), float(self.studyRead))
self.model2.setData(self.model2.index(row, 0, QModelIndex()), QColor("#99e600"), Qt.DecorationRole)
row=1
self.model2.insertRows(row, 1, QModelIndex())
self.model2.setData(self.model2.index(row, 0, QModelIndex()),"미학습")
self.model2.setData(self.model2.index(row, 1, QModelIndex()), float(self.studyTotal-self.studyRead))
self.model2.setData(self.model2.index(row, 0, QModelIndex()), QColor("#8080b3"), Qt.DecorationRole)
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table.setSelectionMode(QAbstractItemView.SingleSelection)
self.table.setDragEnabled(False)
self.table.horizontalHeader().setStretchLastSection(True)
self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.table.resizeRowsToContents()
self.table.resizeColumnsToContents()
self.table.setColumnWidth(0,350)
#self.statusBar().showMessage("Loaded %s" % path, 2000)
def ClickAction_table(self,index):
#self.system
#index.data()
#self.table.selectedIndexes()[0].data()
tempstr = self.table.selectedIndexes()[0].data().split()
filepath = r"PyStudy_web\\example\\기본예제\\"+tempstr[0]+".html"
selectedRowKey = self.table.selectedIndexes()[0].row()+1#mysql 테이블 줄수 차이
#print("click test ",selectedRowKey )
con = sqlite3.connect("mystudy.db")
cur = con.cursor()
cur.execute("update 'study' set 'readcheck'=1 where key="+str(selectedRowKey)+";")
con.commit()
con.close()
self.setupViews()
self.readDB()
self.system.sendMessage("/학습창 열기 "+filepath)
def ClickAction_dbinit(self,index):
con = sqlite3.connect("mystudy.db")
cur = con.cursor()
cur.execute("update 'study' set 'readcheck'=0 ;")
con.commit()
con.close()
self.setupViews()
self.readDB()
示例2: QApplication
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
#self._parent._fileSave()
pass
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication, QTableView
from mtg.Database import CardDatabase
app = QApplication(sys.argv)
db = CardDatabase()
mdl = CubeModel(os.path.abspath(r".\MyCube.xml"), db, parent=app)
mdl._cubeData = etree.parse(mdl._cubeFile)
tbl = QTableView()
tbl.setModel(mdl)
tbl.resize(800, 600)
for i in range(mdl.columnCount()):
tbl.setColumnWidth(i, CARD_WIDTH)
for i in range(mdl.rowCount()):
tbl.setRowHeight(i, CARD_HEIGHT)
tbl.show()
sys.exit(app.exec_())
示例3: Universe
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
class Universe(QGroupBox):
"""
Handle Universe and display its attributes
Only one is created and display universe_selected attributes
"""
def __init__(self, parent):
super(Universe, self).__init__()
# make it available for the whole instance
self.ola = parent.ola
# intialize variable used in ola_connect method
self.old = None
self.universe_selected = None
# Create universe attributes
self.create_attributes()
# Create the view to display values
self.create_tableview()
# Add the previous UI stuffs to a layout
grid = self.create_layout()
self.grid = grid
self.setLayout(grid)
parent.vbox.addWidget(self)
self.parent = parent
def create_attributes(self):
"""
create attributes widget for the universe
"""
self.id = QSpinBox()
self.id.setReadOnly(True)
self.id.setRange(0, 65536)
self.name = QLineEdit()
self.name.textEdited.connect(self.edit_name)
self.name.setFixedWidth(200)
self.merge_mode_label = QLabel('Merge Mode')
self.merge_mode_htp_label = QLabel('HTP')
self.merge_mode_htp = QRadioButton()
self.merge_mode_ltp_label = QLabel('LTP')
self.merge_mode_ltp = QRadioButton()
self.merge_mode_ltp.toggled.connect(self.edit_merge_mode_ltp)
self.merge_mode_htp.toggled.connect(self.edit_merge_mode_htp)
def edit_name(self, name):
if self.universe_selected:
if self.ola.client.SetUniverseName(self.universe_selected.id, name):
self.parent.universes_refresh()
else:
self.parent.status("name edit failed")
if debug:
"edit universe name failed"
def edit_merge_mode_htp(self, state):
if state:
if debug:
print('switch universe to HTP merge mode')
self.edit_merge_mode(1)
def edit_merge_mode_ltp(self, state):
if state:
if debug:
print('switch universe to LTP merge mode')
self.edit_merge_mode(2)
def edit_merge_mode(self, merge_mode):
if self.universe_selected:
if self.ola.client.SetUniverseMergeMode(self.universe_selected.id, merge_mode):
self.parent.universes_refresh()
else:
self.parent.status("merge mode edit failed")
if debug:
"edit universe merge mode failed"
def create_tableview(self):
"""
create the table view for DMX values
"""
self.view = QTableView()
self.view.setSelectionMode(QAbstractItemView.NoSelection)
self.model = UniverseModel(self)
self.view.setModel(self.model)
# set up headers of the QTableView
v_headers = QHeaderView(Qt.Vertical)
self.view.setVerticalHeader(v_headers)
h_headers = QHeaderView(Qt.Horizontal)
self.view.setHorizontalHeader(h_headers)
if debug :
print('how many lines : ', v_headers.count())
print('how many columns : ', h_headers.count())
# set up rows and columns
for col in range(self.model.columnCount()):
self.view.setColumnWidth(col, 28)
for row in range(self.model.rowCount()):
self.view.setRowHeight(row, 20)
self.view.setMinimumHeight(350)
def create_layout(self):
"""
create the layout for the universe display
"""
grid = QGridLayout()
grid.addWidget(self.id, 0, 0, 1, 1)
#.........这里部分代码省略.........
示例4: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
class MainWindow(QMainWindow):
def __init__(self, data):
super().__init__()
self.resize(400, 600)
self.setWindowTitle('Logger Skeleton')
self.statusBar().showMessage("Ready", 2000)
# Make widgets ####################################
self.tabs = QTabWidget(self)
self.setCentralWidget(self.tabs)
# Add tabs
self.table_tab = QWidget(self)
self.stats_tab = QWidget(self)
self.tabs.addTab(self.table_tab, "Table")
self.tabs.addTab(self.stats_tab, "Stats")
# Table tab ###########################################################
self.table_view = QTableView(self.table_tab)
self.text_edit = QPlainTextEdit()
self.btn_add_row = QPushButton("Add a row")
#self.btn_remove_row = QPushButton("Remove selected rows")
table_tab_vbox = QVBoxLayout()
table_tab_vbox.addWidget(self.table_view)
table_tab_vbox.addWidget(self.text_edit)
table_tab_vbox.addWidget(self.btn_add_row)
#table_tab_vbox.addWidget(self.btn_remove_row)
self.table_tab.setLayout(table_tab_vbox)
# Set model #######################################
my_model = DataQtModel(data, parent=self) # TODO: right use of "parent" ?
# Proxy model #####################################
proxy_model = QSortFilterProxyModel(parent=self) # TODO: right use of "parent" ?
proxy_model.setSourceModel(my_model)
self.table_view.setModel(proxy_model)
#self.table_view.setModel(my_model)
# Set the view ####################################
self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows) # Select the full row when a cell is selected (See http://doc.qt.io/qt-5/qabstractitemview.html#selectionBehavior-prop )
#self.table_view.setSelectionMode(QAbstractItemView.SingleSelection) # Set selection mode. See http://doc.qt.io/qt-5/qabstractitemview.html#selectionMode-prop
self.table_view.setAlternatingRowColors(True)
self.table_view.setSortingEnabled(True)
self.table_view.setColumnWidth(0, 200) # TODO: automatically get the best width
self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # https://stackoverflow.com/q/17535563
self.table_view.setColumnHidden(COMMENT_COLUMN_INDEX, True)
delegate = Delegate()
self.table_view.setItemDelegate(delegate)
# Set key shortcut ################################
# see https://stackoverflow.com/a/17631703 and http://doc.qt.io/qt-5/qaction.html#details
# Add row action
add_action = QAction(self.table_view)
add_action.setShortcut(Qt.CTRL | Qt.Key_N)
add_action.triggered.connect(self.add_row_btn_callback)
self.table_view.addAction(add_action)
# Delete action
del_action = QAction(self.table_view)
del_action.setShortcut(Qt.Key_Delete)
del_action.triggered.connect(self.remove_row_callback)
self.table_view.addAction(del_action)
# Set QDataWidgetMapper ###########################
self.mapper = QDataWidgetMapper()
self.mapper.setModel(proxy_model) # WARNING: do not use `my_model` here otherwise the index mapping will be wrong!
self.mapper.addMapping(self.text_edit, COMMENT_COLUMN_INDEX)
self.mapper.toFirst() # TODO: is it a good idea ?
self.table_view.selectionModel().selectionChanged.connect(self.update_selection)
# Set slots #######################################
self.btn_add_row.clicked.connect(self.add_row_btn_callback)
#self.btn_remove_row.clicked.connect(self.remove_row_callback)
#self.table_view.setColumnHidden(1, True)
#.........这里部分代码省略.........
示例5: Example
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
#.........这里部分代码省略.........
for line in k:
if (line[0] != '') and (line[0] != '\t'):
self.cacheIn.append(line)
rowIn = rowIn + 1
self.cacheIn.sort()
self.cacheOut.sort()
if type == 'table':
self.createTable('out', rowOut, self.cacheOut)
self.createTable('in', rowIn, self.cacheIn)
else:
return self.cacheIn, self.cacheOut
cur.close()
db.close()
def procInDisp(self, disp):
"""
Обработка входящих дисциплин для применения в SQL запросах
:param disp:
:return:
"""
m = disp
m = m.strip()
m = m.replace(' ', '_')
m = m.replace(' ', '')
m = m.replace(' ', '')
m = m.replace('-', '_')
m = m.replace('.', '')
m = m.replace('«', '')
m = m.replace('»', '')
m = m.replace(',', '')
m = m.capitalize()
return m
def createTable(self, type_table, rows, list_of_komp):
"""
Создание и заполнение таблицы
:param type_table:
:param row:
:param list_komp:
:param list_desc:
:return:
"""
if type_table == 'out':
model = QStandardItemModel(rows, 2)
list_horizontal = ['Код компетенции', 'Описание компетенции']
model.setHorizontalHeaderLabels(list_horizontal)
self.tableOut.setModel(model)
self.tableOut.setColumnWidth(0, 110)
self.tableOut.setColumnWidth(1, self.tableOut.width() - 130)
for row in range(rows):
for column in range(2):
index = model.index(row, column, QModelIndex())
model.setData(index, str(list_of_komp[row][column]).strip())
else:
model = QStandardItemModel(rows, 2)
list_horizontal = ['Код компетенции', 'Описание компетенции']
model.setHorizontalHeaderLabels(list_horizontal)
self.tableIn.setModel(model)
self.tableIn.setColumnWidth(0, 110)
self.tableIn.setColumnWidth(1, self.tableIn.width() - 130)
for row in range(rows):
for column in range(2):
index = model.index(row, column, QModelIndex())
model.setData(index, str(list_of_komp[row][column]).strip())
def save_one(self):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = str(self.listOfDiscipline.currentText())[:20]
ws.append(['Входящие компетенции'])
for line in self.cacheIn:
ws.append([line[0].strip(), line[1].strip()])
ws.append(['Выходящие компетенции'])
for line in self.cacheOut:
ws.append([line[0].strip(), line[1].strip()])
wb.save(self.listOfDiscipline.currentText() + '.xlsx')
def save_all(self):
count_displ = self.listOfDiscipline.count()
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Дисциплины'
ws['A1'] = 'Сохранениые дисциплины'
for count in range(count_displ):
ws.append([str(self.listOfDiscipline.itemText(count))])
for count in range(count_displ):
inDis, outDis = self.formInComp(self.listOfDiscipline.itemText(count), self.nameFileOpen, ' ')
ws = wb.create_sheet(self.listOfDiscipline.itemText(count)[:20])
ws.append(['Входящие компетенции'])
for line in inDis:
ws.append([line[0].strip(), line[1].strip()])
ws.append(['Выходящие компетенции'])
for line in outDis:
ws.append([line[0].strip(), line[1].strip()])
wb.save('Все дисциплины.xlsx')
示例6: ParamModWgt
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
class ParamModWgt(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.main_window = parent
self.buildRequiredTagsGB()
# Widgets
self.newParamBtn = QPushButton("New")
self.deleteParamBtn = QPushButton("Delete")
self.paramSaveAnnotBtn = QPushButton("Save")
buttonWidget = QWidget(self)
self.existingParamsGB = QGroupBox("Existing parameters", self)
self.paramListTblWdg = QTableView()
self.paramListModel = ParameterListModel(parent=self)
self.paramListTblWdg.setSelectionBehavior(QAbstractItemView.SelectRows)
self.paramListTblWdg.setSelectionMode(QAbstractItemView.SingleSelection)
self.paramListTblWdg.setModel(self.paramListModel)
self.paramListTblWdg.setColumnWidth(0, 150)
self.paramListTblWdg.setColumnWidth(1, 350)
self.relationWgt = ParamRelationWgt(parent)
self.newParamsGB = QGroupBox("Parameter details", self)
self.resultTypeCbo = QComboBox(self)
self.isExpProp = QCheckBox("is an experimental property", self)
self.resultTypeCbo.addItems(["point value", "function", "numerical trace"])
self.singleValueParamWgt = ParamValueWgt(parent)
self.functionParamWgt = ParamFunctionWgt(parent)
self.traceParamWgt = ParamTraceWgt(parent)
self.functionParamWgt.mainWgt = self
self.paramModStack = QStackedWidget(self)
self.paramModStack.addWidget(self.singleValueParamWgt)
self.paramModStack.addWidget(self.functionParamWgt)
self.paramModStack.addWidget(self.traceParamWgt)
# Signals
selectionModel = self.paramListTblWdg.selectionModel()
selectionModel.selectionChanged.connect(self.selectedParameterChanged)
self.newParamBtn.clicked.connect(self.newParameter)
self.deleteParamBtn.clicked.connect(self.deleteParameter)
self.paramSaveAnnotBtn.clicked.connect(self.saveParameter)
self.resultTypeCbo.currentIndexChanged.connect(self.paramModStack.setCurrentIndex)
self.singleValueParamWgt.paramTypeSelected.connect(self.newParamTypeSelected)
self.functionParamWgt.paramTypeSelected.connect(self.newParamTypeSelected)
self.traceParamWgt.paramTypeSelected.connect(self.newParamTypeSelected)
# Layout
buttonLayout = QVBoxLayout(buttonWidget)
buttonLayout.addWidget(self.paramSaveAnnotBtn)
buttonLayout.addWidget(self.deleteParamBtn)
buttonLayout.addWidget(self.newParamBtn)
existGrid = QHBoxLayout(self.existingParamsGB)
existGrid.addWidget(buttonWidget)
existGrid.addWidget(self.paramListTblWdg)
newGrid = QGridLayout(self.newParamsGB)
newGrid.addWidget(QLabel("Result type"), 0, 0)
newGrid.addWidget(self.resultTypeCbo, 0, 1)
newGrid.addWidget(self.isExpProp, 0, 2)
newGrid.addWidget(self.paramModStack, 1, 0, 1, 3)
newGrid.addWidget(self.relationWgt, 1, 3)
layout = QVBoxLayout(self)
self.rootLayout = QSplitter(Qt.Vertical, self)
self.rootLayout.setOrientation(Qt.Vertical)
self.rootLayout.addWidget(self.existingParamsGB)
self.rootLayout.addWidget(self.newParamsGB)
self.rootLayout.addWidget(self.requireTagGB)
layout.addWidget(self.rootLayout)
# Initial behavior
self.newParamBtn.setEnabled(True)
self.deleteParamBtn.setEnabled(False)
self.paramSaveAnnotBtn.setEnabled(False)
self.additionMode = False
self.newParamsGB.setEnabled(False)
def setRootLayoutSizes(self, sizes):
self.rootLayout.setSizes(sizes)
def viewParameter(self, parameter):
row = -1
for row, param in enumerate(self.paramListModel.parameterList):
if param.id == parameter.id:
break
assert(row > -1)
self.paramListTblWdg.selectRow(row)
#.........这里部分代码省略.........
示例7: FreezeTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setColumnWidth [as 别名]
class FreezeTableWidget(QTableView):
def __init__(self, model):
super(FreezeTableWidget, self).__init__()
self.setModel(model)
self.frozenTableView = QTableView(self)
self.init()
self.horizontalHeader().sectionResized.connect(self.updateSectionWidth)
self.verticalHeader().sectionResized.connect(self.updateSectionHeight)
self.frozenTableView.verticalScrollBar().valueChanged.connect(
self.verticalScrollBar().setValue)
self.verticalScrollBar().valueChanged.connect(
self.frozenTableView.verticalScrollBar().setValue)
def init(self):
self.frozenTableView.setModel(self.model())
self.frozenTableView.setFocusPolicy(Qt.NoFocus)
self.frozenTableView.verticalHeader().hide()
self.frozenTableView.horizontalHeader().setSectionResizeMode(
QHeaderView.Fixed)
self.viewport().stackUnder(self.frozenTableView)
self.frozenTableView.setStyleSheet('''
QTableView { border: none;
background-color: #8EDE21;
selection-background-color: #999;
}''') # for demo purposes
self.frozenTableView.setSelectionModel(self.selectionModel())
for col in range(1, self.model().columnCount()):
self.frozenTableView.setColumnHidden(col, True)
self.frozenTableView.setColumnWidth(0, self.columnWidth(0))
self.frozenTableView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.frozenTableView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.frozenTableView.show()
self.updateFrozenTableGeometry()
self.setHorizontalScrollMode(self.ScrollPerPixel)
self.setVerticalScrollMode(self.ScrollPerPixel)
self.frozenTableView.setVerticalScrollMode(self.ScrollPerPixel)
def updateSectionWidth(self, logicalIndex, oldSize, newSize):
if self.logicalIndex == 0:
self.frozenTableView.setColumnWidth(0, newSize)
self.updateFrozenTableGeometry()
def updateSectionHeight(self, logicalIndex, oldSize, newSize):
self.frozenTableView.setRowHeight(logicalIndex, newSize)
def resizeEvent(self, event):
super(FreezeTableWidget, self).resizeEvent(event)
self.updateFrozenTableGeometry()
def moveCursor(self, cursorAction, modifiers):
current = super(FreezeTableWidget, self).moveCursor(cursorAction, modifiers)
if (cursorAction == self.MoveLeft and
self.current.column() > 0 and
self.visualRect(current).topLeft().x() <
self.frozenTableView.columnWidth(0)):
newValue = (self.horizontalScrollBar().value() +
self.visualRect(current).topLeft().x() -
self.frozenTableView.columnWidth(0))
self.horizontalScrollBar().setValue(newValue)
return current
def scrollTo(self, index, hint):
if index.column() > 0:
super(FreezeTableWidget, self).scrollTo(index, hint)
def updateFrozenTableGeometry(self):
self.frozenTableView.setGeometry(
self.verticalHeader().width() + self.frameWidth(),
self.frameWidth(), self.columnWidth(0),
self.viewport().height() + self.horizontalHeader().height())