Qt6免继承实现QTableWidget右键菜单

通过事件过滤器(eventFilter)来实现右键菜单并显示行号。这种方法更加灵活,适合在已有的 QTableWidget 上添加功能,而无需修改或继承它。

以下是完整的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <QApplication>
#include <QTableWidget>
#include <QMenu>
#include <QContextMenuEvent>
#include <QMessageBox>
#include <QHBoxLayout>
#include <QWidget>

int main(int argc, char *argv[]) {
QApplication app(argc, argv);

// 创建主窗口
QWidget window;
QHBoxLayout *layout = new QHBoxLayout(&window);

// 创建 QTableWidget
QTableWidget *tableWidget = new QTableWidget(5, 3);
tableWidget->setHorizontalHeaderLabels({"Column 1", "Column 2", "Column 3"});

// 填充一些数据
for (int row = 0; row < 5; ++row) {
for (int col = 0; col < 3; ++col) {
QTableWidgetItem *item = new QTableWidgetItem(tr("Item %1-%2").arg(row).arg(col));
tableWidget->setItem(row, col, item);
}
}

// 将 QTableWidget 添加到布局中
layout->addWidget(tableWidget);
window.setLayout(layout);

// 安装事件过滤器
tableWidget->viewport()->installEventFilter(&window);

// 事件过滤器实现
window.installEventFilter(tableWidget);
QObject::connect(tableWidget, &QTableWidget::customContextMenuRequested, [tableWidget](const QPoint &pos) {
QTableWidgetItem *item = tableWidget->itemAt(pos);
if (item) {
int row = item->row();

// 创建右键菜单
QMenu menu;
QAction *showRowAction = menu.addAction(tr("Show Row Number"));
QObject::connect(showRowAction, &QAction::triggered, [row]() {
QMessageBox::information(nullptr, tr("Row Number"), tr("You clicked on row: %1").arg(row));
});

// 显示菜单
menu.exec(tableWidget->viewport()->mapToGlobal(pos));
}
});

// 启用右键菜单
tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);

window.show();
return app.exec();
}

代码说明:

Read More

嵌入的Qt对话框输入一些东西相关(.exec/.show etc)

基本框架

1
2
3
4
5
6
7
8
9
10
11
12
13

# some content load from remote data service
# ... code ignored ...

app = QApplication([])
dialog = ContentEditDialog(original_content)
dialog.exec()
# dialog.show()
# app.exec()

updated_content = dialog.collect_edited_content()

print(updated_content)
  • 只有dialog.exec():程序阻塞,编辑生效。
  • 只有dialog.show(): 程序不阻塞,对话框一闪即逝,无法编辑。
Read More

Windows端口成为系统保留端口的问题

问题背景

因为要使用Redis,所以装了WSL,但启动后发现SS打不开了,提示xxx端口被系统保留。

参考文后所附文章:

  • Windows 中有一个「TCP 动态端口范围」,处在这个范围内的端口,有时候会被一些服务占用。在 Windows Vista(或 Windows Server 2008)之前,动态端口范围是 1025 到 5000;在 Windows Vista(或 Windows Server 2008)之后,新的默认起始端口为 49152,新的默认结束端口为 65535。
Read More

Github:解除Fork关系

开发者在利用GitHub进行项目开发时,常会遇到与Fork操作相关的一系列挑战,尤其是在项目独立发展后,这些挑战尤为突出。以下是几个关键问题及其有条理的重述:

1. 项目独立发展后的管理难题
  • 深度定制与分化:最初通过Fork一个仓库开始的项目,随着时间推移,可能经历了从功能扩展到开发语言的变更,导致该仓库与原始父仓库在各个方面都已显著分化,各自独立发展。

Read More