QTableWidget - 将Button拖放到QTableWidget中的单元格中

时间:2012-05-09 21:14:30

标签: python pyqt

当我将按钮拖放到QTableWidget中时,按钮从旧位置开始消失,并且在我按下按钮的单元格中没有显示任何内容。

有人能说出问题是什么吗?

请在下面找到代码

import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class Button(QtGui.QPushButton):

    def __init__(self, title, parent):
        super(Button, self).__init__(title, parent)

    def mouseMoveEvent(self, e):
        if e.buttons() != QtCore.Qt.RightButton:
            return 

        mimeData = QtCore.QMimeData()
        drag = QtGui.QDrag(self)
        drag.setMimeData(mimeData)
        drag.setHotSpot(e.pos() - self.rect().topLeft())

        dropAction = drag.start(QtCore.Qt.MoveAction)

    def mousePressEvent(self, e):
        if e.button() == QtCore.Qt.LeftButton:
            print 'Left Button Pressed'


class MyTable(QtGui.QTableWidget):

    def __init__(self, rows, columns, butObject, parent):
        super(MyTable, self).__init__(rows, columns, parent)
        self.setAcceptDrops(True)
        self.butObject = butObject

    def dragEnterEvent(self, e):
        e.accept()

    def dropEvent(self, e):
        position = e.pos()

        print position

        self.butObject.move(position)

        e.setDropAction(QtCore.Qt.MoveAction)
        e.accept()

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

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.setAcceptDrops(True)

        self.button = Button('Button', self)
        self.button.move(50, 200)

        self.table = MyTable(2, 2, self.button, self)
        self.table.setAcceptDrops(True)
        self.table.setDragEnabled(True)

        self.setWindowTitle('Click or Move')
        #self.setGeometry(300, 300, 280, 150)

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()

if __name__ == '__main__':
    main()  

1 个答案:

答案 0 :(得分:3)

当您将按钮放入表格时,“打印位置”是否有效?它应该将掉落位置的坐标打印到你的外壳上。 我认为您需要使用它们然后将按钮插入表格。

让它工作 - 将你的掉落事件改为:

    position = e.pos()

    print position

    row = self.rowAt(position.y())

    column = self.columnAt(position.x())

    self.setCellWidget(row,column,self.butObject)

    e.setDropAction(QtCore.Qt.MoveAction)
    e.accept()

干杯

戴夫