Issue
I tried change QTableWidgetItem font, and complete that.
But, In Editmode, not change font.
(PS. I shouldn't give same style, so i don't use qss style sheet)
Below code, If Input F1 key, Size up current cell font size.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class MainWindow(QMainWindow):
def __init__(self, **kwargs):
super().__init__()
self.init_main()
self.init_table()
self.resize(500,500)
self.show()
def init_main(self):
self.main_widget = QWidget()
self.main_layout = QHBoxLayout()
self.main_widget.setLayout(self.main_layout)
self.setCentralWidget(self.main_widget)
def init_table(self):
self.table = QTableWidget(5, 5, self)
self.table.resize(500, 500)
# init QTableWidgetItem in QTableWidget (5 x 5),
[[self.table.setItem(row, col,QTableWidgetItem("text")) for row in range(5)] for col in range(5)]
def keyPressEvent(self, e):
# If input F1, resize font-size in current item.
if e.key() == Qt.Key_F1:
cur = self.table.currentItem()
font = cur.font()
font.setPointSize(30)
cur.setFont(font)
if __name__ == "__main__":
app = QCoreApplication.instance()
if app is None:
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
Solution
Setting the font on an item just changes the font for that item, not for its editor.
What you need to do is to create an item delegate (which is an object that is responsible of showing items and provide interaction with the underlying model, including the appropriate editor).
Since setting the font on a QTableWidgetItem equals to set the Qt.FontRole
of the index, you can easily access that from the createEditor()
function, call the base implementation to get the editor that is going to be returned, and apply the font to it if a font is set.
class FontDelegate(QStyledItemDelegate):
def createEditor(self, parent, opt, index):
editor = super().createEditor(parent, opt, index)
font = index.data(Qt.FontRole)
if font is not None:
editor.setFont(font)
return editor
class MainWindow(QMainWindow):
# ...
def init_table(self):
self.table = QTableWidget(5, 5)
self.main_layout.addWidget(self.table)
[[self.table.setItem(row, col, QTableWidgetItem("text")) for row in range(5)] for col in range(5)]
self.table.setItemDelegate(FontDelegate(self.table))
# ...
Unrelated note: the table should be added to the layout (as I did in the above code), and not just created as a child of the main window.
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.