2012-08-31 61 views
0

如何在每次單擊時將鼠標點擊座標附加到QTableWidget?我已經有QMouseEvent顯示QLabelItem中的座標,但我想添加一行每個點擊的座標。這可能嗎?我知道我需要使用setItem(),但我如何將它附加到現有的鼠標點擊事件?將鼠標位置寫入QTableWidget

這裏的事件過濾器,我有鼠標點擊:

def eventFilter(self, obj, event): 
     if obj is self.p1 and event.type() == event.GraphicsSceneMousePress: 
      if event.button()==Qt.LeftButton: 
       pos=event.scenePos() 
       x=((pos.x()*(2.486/96))-1) 
       y=(pos.y()*(10.28/512)) 
       self.label.setText("x=%0.01f,y=%0.01f" %(x,y)) 
     #here is where I get lost with creating an iterator to append to the table with each click 
      for row in range(10): 
       for column in range(2): 
        self.coordinates.setItem(row,column,(x,y)) 
+1

你想每次** **添加一個新行,或你想更新現有的單元格? – jdi

+0

添加一個新行...我不太喜歡迭代,所以這就是我一直陷入困境的地方 –

+0

爲什麼要爲表中的多個單元添加相同的'(x,y)'字符串值?這是你的目標還是你只想添加一個新的單元格在一個新的行? – jdi

回答

1

假設你已經爲x,y值的兩列的表,並要追加一個新行,每次點擊:

def eventFilter(self, obj, event): 
    if obj is self.p1 and event.type() == event.GraphicsSceneMousePress: 
     if event.button() == Qt.LeftButton: 
      pos = event.scenePos() 
      x = QtGui.QTableWidgetItem(
       '%0.01f' % ((pos.x() * 2.486/96) - 1)) 
      y = QtGui.QTableWidgetItem(
       '%0.01f' % (pos.y() * 10.28/512)) 
      row = self.coordinates.rowCount() 
      self.coordinates.insertRow(row) 
      self.coordinates.setItem(row, 0, x) 
      self.coordinates.setItem(row, 1, y) 
+0

這工作很好,謝謝!過度思考,一如既往...... –

1

假設model=QTableView.model(),你可以添加一個新行到你的表是這樣的:

nbrows = model.rowCount() 
model.beginInsertRows(QModelIndex(),nbrows,nbrows) 
item = QStandardItem("({0},{1})".format(x,y)) 
model.insertRow(nbrows, item.index()) 
model.endInsertRows() 

如果你有一個QTableWidget而不是一個QTableView,你可以使用相同的MO:

  • 追加新行self.insertRow(self.rowCount())
  • 使用.setItem方法修改最後一行的數據。你可以使用例如QTableWidgetItem("({0},{1})".format(x,y)),或者任何你喜歡用來表示你的座標元組的字符串。

不過,我建議你開始使用QTableView S的替代QTableWidget,因爲它提供了更大的靈活性。

+0

因爲setItem方法,我感覺它是一個QTableWidget。 – jdi

+0

事實上,OP提到它。我忽略了這一點。 –

+0

既不是石頭;我可以很容易地拋棄它爲QTableView ...我同意,可能是更好的選擇。謝謝! –