1

当我将按钮拖放到 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()  
4

1 回答 1

3

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

让它工作 - 将你的 drop 事件更改为:

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

干杯

戴夫

于 2012-05-10T11:06:12.020 回答