无法在 PyQt5 中打印点击的行

Not able to print clicked line in PyQt5

我正在使用 QTextBrowser 打印数据,但想检查哪一行被点击并获取它的字符串。我查看了其他资源并能够做到这一点,但它没有打印该行。

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class TextBrowser(QtWidgets.QTextBrowser):

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseButtonPress:
            tc = self.cursorForPosition(event.pos())
            print("text = ", tc.block().text())
        return super().eventFilter(source, event)

    def setupUi(self, MainWindow):
        MainWindow.resize(104, 105)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget") 
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName(u"gridLayout_8")
        self.code_textBrowser = QtWidgets.QTextBrowser(self.centralwidget)

        self.gridLayout.addWidget(self.code_textBrowser, 1, 0, 1, 1)
        self.code_textBrowser.viewport().installEventFilter(self)
        self.code_textBrowser.append("ab\ncde\nfghi\njklmn\nopqrstu")

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        MainWindow.setMenuBar(self.menubar)
    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = TextBrowser()
    ui.setupUi(MainWindow)    
    MainWindow.show()
    sys.exit(app.exec_())

我不建议修改 .ui 生成的代码的原因之一是它会导致混淆,因此对于我可能的解决方案,您必须恢复该文件 (运行 pyuic)并将生成的文件称为 gui.py.

问题是 cursorForPosition returns 光标与“TextBrowser”(在您的情况下为“ui”)相关联,而不是与“code_textBrowser”相关联,class 继承自 class T 并不意味着所有属性都相同 class T 它们将是相同的。

解决方案是在另一个 class 中实现逻辑,它继承自 QObject,如 QMainWindow,并使用 code_textBrowser.

实现逻辑
import sys

from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QApplication, QMainWindow

from gui import Ui_MainWindow


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.code_textBrowser.viewport().installEventFilter(self)

    def eventFilter(self, obj, event):
        if (
            obj is self.ui.code_textBrowser.viewport()
            and event.type() == QEvent.MouseButtonPress
        ):
            tc = self.ui.code_textBrowser.cursorForPosition(event.pos())
            print("text = ", tc.block().text())

        return super().eventFilter(obj, event)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    w = MainWindow()
    w.show()

    sys.exit(app.exec_())