0

このようにリストビューでを上書きしcontentsMousePressEventました。

void AppListView::contentsMousePressEvent(QMouseEvent *e)
{
    AppGenericListView::contentsMousePressEvent(e);
    if (e->button() == Qt::RightButton)
        emit rightClicked();
    emit multiSelection();
}

これが私のkeyPressEventです。

void AppListView::keyPressEvent(QKeyEvent * e)
{
    AppGenericListView::keyPressEvent(e);
    if ((e->key() == Qt::Key_Up) || (e->key() == Qt::Key_Down))
    {
        QListViewItem * item = currentItem();
        if (item)
        {
            const QRect rect = itemRect(item);
            QMouseEvent mEvt(QEvent::MouseButtonPress, rect.center(), Qt::LeftButton, Qt::LeftButton);
            contentsMousePressEvent(&mEvt);
        }
    }
}

今のところ、このコードは正常に機能しています。QMouseEvent動的オブジェクトを作成していないことに注意してください。私が知りたいのは、これは将来クラッシュを引き起こすのでしょうか?contentMousePressEvent動的オブジェクトが必要ですか?Qtdocはそれについて多くを語っていません。何か案は ....

4

2 に答える 2

1

イベントハンドラーは、受信したイベントの所有権を取得しません。したがって、現在のコードは問題ありません。

QCoreApplication::postEvent非同期で送信するように渡すと、自動的に削除されます(そしてクラッシュが発生します) 。

于 2012-09-24T13:46:07.027 に答える
1

It won't crash, because you are not using event loop. But i think you should, for two reasons:

  1. You are simulating mouse press event but you are not serving it to the object as a such. For example, you don't serve your fake mouse event to mousePressEvent(). So for "natural" mouse press events and your simulated one, the application will behave differently. And you may forget why is that and you may get inexplicable crashes when your code evolves.

  2. The original system keypress event handling will be blocked by handling a mouse press event. You can't know who (what thread) will connect() to your signals emitted from overriden mouse event handler. Don't be surprised if you get a deadlock.

Such a half baked shortcuts are good only as temporary solutions. In the long run, they will shoot at your back. If you really want a shortcut, stop pretending it's a mouse event and implement a special separate method which will be called also from the "real" mouse event. If you want a real mouse event, handled properly, create a dynamic QMouseEvent and enqueue it at the event loop.

QMouseEvent* evt = new QMouseEvent(QEvent::MouseButtonPress,
  rect.center(),this->mapToGlobal(rect.center()),
 Qt::LeftButton, Qt::LeftButton);
QCoreApplication::postEvent(this,evt);
于 2012-09-24T14:15:56.740 に答える