python - 在PYQT中选择要复制的文本

标签 python pyqt5 pyqt4 qt-designer qtablewidget

我使用 QT Designer 和 PYQT5 设计了一个 Windows 桌面应用程序。问题是,我无法选择主窗口或 qtablewidget 上的任何项目、文本来手动将其粘贴到其他地方。它将使用户的事情变得更容易,而不是对我来说。 `

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(260, 160, 256, 192))
        self.tableWidget.setRowCount(3)
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setObjectName("tableWidget")
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(1, 0, item)
        self.input_gunduz = QtWidgets.QLineEdit(self.centralwidget)
        self.input_gunduz.setGeometry(QtCore.QRect(370, 70, 71, 20))
        self.input_gunduz.setObjectName("input_gunduz")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(220, 70, 101, 21))
        font = QtGui.QFont()
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        item = self.tableWidget.item(1, 0)
        item.setText(_translate("MainWindow", "trial"))
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.label_5.setText(_translate("MainWindow", "Gündüz (kWhr):"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

`

代码如上所示。请帮助我使主窗口可选择

最佳答案

文本复制对于每个小部件的工作方式并不相同,因为每个小部件类型甚至使用完全不同的方式来显示文本或与文本交互。

如果您想复制 QLabel 的文本,则必须使其可选择(通过使用 label.setTextInteractionFlags(Qt.TextSelectableByMouse) )。

但是,如果您想从 QTableWidget 复制文本,情况就大不相同了,因为表格允许与其项目进行交互,从而阻止简单的文本选择。

显然,最简单的方法是开始编辑项目(假设它是可编辑的)并选择其文本,但如果您想要其他方法来做到这一点,则取决于您想要的方式能够复制文本。

可以使用 ctrl+c 键盘快捷键。为此,我们需要在表格小部件上安装事件过滤器:

from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # install an event filter on the table widget, so that we can filter all
        # its event, including keyboard presses
        self.tableWidget.installEventFilter(self)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.KeyPress and event == QtGui.QKeySequence.Copy:
            # check if an index is currently selected and it has text
            text = self.tableWidget.currentIndex().data()
            if text:
                # copy that text to the clipboard
                QtWidgets.QApplication.clipboard().setText(text)
        return super().eventFilter(source, event)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

请注意,在上面的示例中,我使用了有关 using Designer 的文档中解释的多重继承方法。与 ui 文件。您不应该永远编辑pyuic创建的文件。

还可以为表格小部件设置菜单并从那里复制文本:

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        # ...

        # use the custom context menu policy for the table widget, so that we can
        # connect the menu request to a slot
        self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.tableWidget.customContextMenuRequested.connect(self.showTableMenu)

    def showTableMenu(self, pos):
        # get the text of the index at the mouse cursor (if any)
        text = self.tableWidget.indexAt(pos).data()
        menu = QtWidgets.QMenu()
        copyAction = menu.addAction('Copy')
        if not text:
            copyAction.setEnabled(False)
        # show the menu
        res = menu.exec_(QtGui.QCursor.pos())
        if res == copyAction:
            # if the menu has been triggered by the action, copy to the clipboard
            QtWidgets.QApplication.clipboard().setText(text)

关于python - 在PYQT中选择要复制的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61401792/

相关文章:

python - 如何通过python读取apache beam(数据流)中的JSON文件?

python - 在 PyQt 中透明地获取退格事件

python - 在BuildBot构建步骤中调用Python方法

python - 如何修复Python类中的属性错误

python - 如何自定义 python PyQt5 QWebEngineView 上下文菜单?

python - 将 QPixmap 保存到 PostgreSQL 而不使用准备好的查询

python - 如何使用 PyQt 在窗口中切换布局? (不关闭/打开 window )

python - pyqt qtabwidget QtDesigner中的水平选项卡和水平文本

python - 无法从 PyQt4 导入 QtGui

python - 如何使用 __pycache__ 文件夹运行 Python 项目?