当您将鼠标信号从模型插入插槽时,传递的参数是QModelIndex。
QModelIndex不会告诉您按下了什么按钮。因此,我们可以求助于QApplication :: mouseButtons。但是QApplication :: mouseButtons是当前的按钮按下,而不是模型经历点击时。
我的思想实验是说,按下右键后,基础视图将信号发送到我的小部件,但是在我的小部件的插槽接收到该信号之前,发生了虚假的左键单击。因此,在收到QModelIndex时调用QApplication :: mouseButtons将错误地将正在单击的行与鼠标左键而不是右键相关联。这种情况怎么可能?
当您查看Qt甚至QML时,需要大量的代码技巧才能在收到QModelIndex后获得正确的鼠标按钮信息。诺基亚是否正在努力促进鼠标不可知论的政策?
最佳答案
我认为这不太可能,但是有可能发生。
确保单击哪个按钮的“简单”方法是将QTableView
子类化(或使用的视图并重新实现mouseReleaseEvent
)。
void mouseReleaseEvent(QMouseEvent * event)
{
// store the button that was clicked
mButton = event->button();
// Now call the parent's event
QTableView::mouseReleaseEvent(event);
}
默认情况下,如果按下视图的某个项目,
mouseReleaseEvent
会发出clicked
信号如果用户在小部件内按下鼠标,然后拖动
在释放鼠标按钮之前,将鼠标移至其他位置
小部件收到释放事件。该函数将发出
clicked()表示是否已按下某个项目。
诀窍是在派生类中捕获
clicked
信号并发出一个新信号,除了模型索引也将包含按钮。// Define your new signal in the header
signals:
void clicked(QModelIndex, Qt::MouseButton);
// and a slot that will emit it
private slots:
void clickedSlot(QModelIndex);
// In the constructor of your derived class connect the default clicked with a slot
connect(this, SIGNAL(clicked(QModelIndex), this, SLOT(clickedSlot(QModelIndex)));
// Now the slot just emits the new clicked signal with the button that was pressed
void clickedSlot(QModelIndex i)
{
emit clicked(i, mButton);
}
如果还需要
mousePressEvent
信号,则可以使用pressed
做类似的事情。