Reputation: 9451
I am trying to set font of QTextEdit
to be the same as of QTreeWidget
.
When I get the font from QTextEdit
and try to set it to QTreeWidget
, it does not work. However, if I create a new font QFont("Segoe UI", 9)
, which happens to be the same as QTreeWidget
has on my platform (Windows 7) and set it to QTextEdit
, it works.
The following code prints True
for the font comparison, but does not work as expected. Uncommenting the self.text.setFont(new_font)
fixes it. Why?
import string
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont
TEXT = string.printable[:-5]
def print_font(font):
print("Family: {}, Size: {}".format(font.family(), font.pointSize()))
class Window(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.list = QTreeWidget(self)
self.list.addTopLevelItem(QTreeWidgetItem((TEXT,)))
self.list.setRootIsDecorated(False)
self.list.setHeaderHidden(True)
self.list.setMinimumHeight(25)
self.text = QTextEdit(self)
self.text.setText(TEXT)
self.text.setMinimumHeight(25)
self.layout = QGridLayout()
self.layout.setContentsMargins(5, 5, 5, 5)
self.layout.addWidget(self.list)
self.layout.addWidget(self.text)
self.resize(620, 20)
self.setLayout(self.layout)
self.show()
list_font = self.list.font()
new_font = QFont("Segoe UI", 9)
print(list_font == new_font)
self.text.setFont(list_font)
# self.text.setFont(new_font)
print_font(self.list.font())
print_font(self.text.font())
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
Upvotes: 3
Views: 1708
Reputation: 120578
You can't safely assume that the properties reported by QFont are the same as those that are actually used. They may be, but it's not guaranteed.
To safely get the actual values used, you need to use QFontInfo. On Linux, I get different values from QFont and QFontInfo, but the font transfer succeeds; on Windows, they're the same, but the transfer fails. Huh.
Anyway, there seems to be some issue with copying fonts on Windows, but I'm unable to diagnose exactly what it might be. Something to do with the font-cache, maybe?
I thought that:
list_font = QFont(self.list.font())
might make a difference - but it doesn't. In the end, the only thing that worked for me on Windows was this:
list_font = QFont()
list_font.fromString(self.list.font().toString())
self.text.setFont(list_font)
Upvotes: 4