如何在另一个小部件的拖放事件期间突出显示表格单元格

时间:2018-11-24 20:41:45

标签: python pyqt pyqt5 qtablewidget

有两个可停靠的小部件:一个带有图标(QLabel),另一个带有表(QTableWidget)。

在第二个窗口小部件的拖放事件期间,我一直试图在鼠标悬停时实现表格的单元格颜色。问题是他们不这样做。表格的类很简单,添加了用于悬停的事件过滤器。

class TableEdit(QtWidgets.QTableWidget):
    def __init__(self, parent=None):
        super(TableEdit, self).__init__(parent=parent)

        # self.setMinimumSize(QtCore.QSize(self.width(), self.height()))

        self.current_hover = [0, 0]
        row = 3
        column = 3

        self.setColumnCount(column)
        self.setAlternatingRowColors(True)

        self.setRowCount(row)

        for row in range(0, 3):
            for column in range(0, 3):
                item = QtWidgets.QTableWidgetItem("This is cell {} {}".format(row + 1, column + 1))
                self.setItem(row, column, item)

        self.setHorizontalHeaderItem(0, QtWidgets.QTableWidgetItem("Col1"))
        self.horizontalHeader().setVisible(False)
        # self.setShowGrid(False)

        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
        self.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)

        self.setAcceptDrops(True)
        self.setMouseTracking(True)
        self.cellEntered.connect(self.cellHover)

    def cellHover(self, row, column):
        item = self.item(row, column)
        old_item = self.item(self.current_hover[0], self.current_hover[1])
        if self.current_hover != [row, column]:
            old_item.setBackground(QtGui.QBrush(QtGui.QColor('white')))
            item.setBackground(QtGui.QBrush(QtGui.QColor('yellow')))
        self.current_hover = [row, column]

    def dragEnterEvent(self, event):
        event.accept()
        print("drag enter +")

    def dragMoveEvent(self, event):
        event.accept()

    def dropEvent(self, event):
        event.accept()
        print("drop +")

        mime = event.mimeData()
        if mime.hasFormat("application/x-fire"):
            print("Fire")

下面的屏幕快照显示,将QLabel拖到单元格中没有任何反应。

1 个答案:

答案 0 :(得分:0)

您必须实现dragMoveEvent方法并实现颜色的逻辑,要获得该项,您必须使用QCursor的位置:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new ClassPathResource("SpringConfig.xml").getPath());
        com.mkyong.repo.BookRepo bookRepo = context.getBean(com.mkyong.repo.BookRepo.class);
        com.mkyong.model.Book hobbit = new com.mkyong.model.Book();
        hobbit.setId("3");
        hobbit.setTitle("Hobbit");
        hobbit.setDescription("Prelude to LOTR");
        //bookRepo.save(hobbit);
        mongoOperation.save(hobbit);
        //solrOperation.saveBean("book", hobbit);       

        System.out.println("#@$@ bookRepo.findOne(3l) ="+bookRepo.findOne(3l));
        System.out.println("@!$@ bookRepo.findByBookTitle(\"Hobbit\") ="+bookRepo.findByBookTitle("Hobbit"));

        context.close();