背景
我正在使用 Python 开发一个图形化的 ssh 客户端。我将 PySide 用于 GUI,将 Paramiko 的一个分支用于 ssh 交互,将一个名为 Pyte 的库用于终端仿真。
问题
我不知道如何根据正在调整大小的 PySide QTextEdit 正确调整 pyte 终端的大小。我似乎只能以像素为单位获取 QTextEdit 的宽度和高度,而不是 pyte 库的 Screen.resize() 函数所需的列和行。
无论如何,1. 获取 QTextEdit 的列数和行数,或者 2. 以在所有系统中都准确的方式将像素宽度和高度转换为列数和行数?
建议的解决方案
用自定义调整大小事件处理程序替换 QTextEdit.resizeEvent() 函数,它将调用 pyte 的 Screen.resize() 函数来调整终端大小以匹配 QTextEdit 小部件的新大小。
如果有更简单的解决方案,我非常乐意接受。
请您参考如下方法:
解决方案
我最终提取了我正在使用的小部件 (QTextEdit) 的字体规范和几何信息。然后我为 QTextEdit 实现了一个自定义调整大小事件,它处理导致更新的不同事件的捕获状态(请参阅下面代码块中我的 resizeConsoleEvent 中的第一个 if 语句),然后计算新的可用列和行并将它们传递给ssh 对象(下面的 self.shell)。
代码
def resizeConsoleEvent(self, resizeObject):
if not self.keyPressDown and not self.blockResizing:
# calculate maximum columns and lines based on a '|' character
font = self.ui.console.currentFont()
fmetric = QtGui.QFontMetrics(font)
fontPixelWidth = fmetric.width("|")
fontPixelHeight = fmetric.height()
availableWidthPixels = int(self.ui.console.geometry().width())
availableHeightPixels = int(self.ui.console.geometry().height())
# Calculate columns and lines w/ adjustments for rounding
self.consoleColumns = int(availableWidthPixels / fontPixelWidth) + 1
self.consoleLines = int(availableHeightPixels / fontPixelHeight) - 3
# resize the pyte screen I'm using with the calculated information
self.shell.resizeConsole(self.consoleLines, self.consoleColumns)
# block double resize event
self.keyPressDown = False
return False
else:
return True
