English 中文(简体)
在PYQT选定一个文本以复制
原标题:Select a text in PYQT to copy

我设计了一个配有QT设计器和PYQT5的窗.。 问题在于,我无法选择任何项目、主要窗口的案文或板块,以人工方式在其他地方加以复制。 这将使用户比我更容易一些。

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_())

守则见上文。 请帮助我选择主要窗口

问题回答

Copying of text does not work in the same way for every widget, because each widget type uses even radically different way to show or interact with text.

如果你想要复制QLabel的案文,你必须将其选用(通过label.setTextactionFlags(Qt.TextSelectableByMouse))。

但是,如果你想要复制QTableWidget的案文,情况就大不相同,因为表格允许与它们的项目进行互动,从而避免简单的案文选择。

显然,最简单的方法是开始编辑该项目(假定其为编辑),并选择其案文,但如果你想以其他方式这样做,则取决于how<>>。

一种可能性是使用 c+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_())

请注意,在上述例子中,我使用了有关,使用设计人和ui文档。 页: 1

还可以确定一张表菜单,复制该表的案文:

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)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...