用qtablewidget类写一个16进制显示器
时间: 2023-05-14 10:07:05 浏览: 133
可以使用以下代码实现:
```python
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem
from PyQt5.QtCore import Qt
class HexViewer(QTableWidget):
def __init__(self, rows, cols):
super().__init__(rows, cols)
self.setHorizontalHeaderLabels(['Address', 'Hex', 'ASCII'])
self.verticalHeader().setVisible(False)
self.setEditTriggers(QTableWidget.NoEditTriggers)
self.setSelectionBehavior(QTableWidget.SelectRows)
self.setSelectionMode(QTableWidget.NoSelection)
self.setShowGrid(False)
self.setColumnWidth(0, 80)
self.setColumnWidth(1, 200)
self.setColumnWidth(2, 200)
self.setStyleSheet('QHeaderView::section { background-color: #f0f0f0; }')
def setData(self, data):
self.setRowCount(len(data))
for i, row in enumerate(data):
address = QTableWidgetItem('{:08X}'.format(i))
address.setTextAlignment(Qt.AlignCenter)
self.setItem(i, 0, address)
hex_data = ' '.join('{:02X}'.format(b) for b in row)
hex_item = QTableWidgetItem(hex_data)
hex_item.setTextAlignment(Qt.AlignCenter)
self.setItem(i, 1, hex_item)
ascii_data = ''.join(chr(b) if 32 <= b <= 126 else '.' for b in row)
ascii_item = QTableWidgetItem(ascii_data)
ascii_item.setTextAlignment(Qt.AlignCenter)
self.setItem(i, 2, ascii_item)
if __name__ == '__main__':
app = QApplication([])
viewer = HexViewer(16, 3)
data = [
[0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64],
[0x21, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61],
[0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x66, 0x69, 0x6C, 0x65, 0x2E],
[0x20, 0x49, 0x74, 0x20, 0x77, 0x6F, 0x72, 0x6B, 0x73, 0x21, 0x21],
]
viewer.setData(data)
viewer.show()
app.exec_()
```
这段代码使用了 PyQt5 库中的 QTableWidget 类来实现一个简单的 16 进制显示器。它将数据按照 16 字节一行的方式显示出来,每行包括地址、16 进制数据和 ASCII 码三列。其中,地址列显示当前行的起始地址,16 进制数据列显示当前行的 16 个字节的 16 进制表示,ASCII 码列显示当前行的 16 个字节的 ASCII 码表示,不可编辑。
阅读全文