【问题标题】:QGraphicsItem loses focus after using QComboBox使用 QComboBox 后 QGraphicsItem 失去焦点
【发布时间】:2017-12-07 08:56:14
【问题描述】:

我在Qt中做一个小游戏,尝试用WASD来移动我的主角(QGraphicsPixmapItem)。地图很大,所以我使用 QComboBox 来改变场景的比例。

游戏是这样的:

简单的游戏

我是如何塑造主角的:

protagonist = new MyProtagonist();
protagonist->setFlag(QGraphicsItem::ItemIsFocusable);
protagonist->setFocus();
scene->addItem(protagonist);

我是如何构建组合框的:

sceneScaleCombo = new QComboBox;
QStringList scales;
scales << tr("1%")<<tr("10%") << tr("20%") <<tr("50%") << tr("100%") <<tr("200%");
sceneScaleCombo->addItems(scales);
sceneScaleCombo->setCurrentIndex(4);
connect(sceneScaleCombo,SIGNAL(currentIndexChanged(QString)),this,SLOT(sceneScaleChanged(QString)));

void MainWindow::sceneScaleChanged(const QString &scale)
{
    double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100;
    QMatrix oldMatrix = view->matrix();
    view->resetMatrix();
    view->translate(oldMatrix.dx(),oldMatrix.dy());
    view->scale(newScale,newScale);
    protagonist->setFocus();
}

一开始一切都很顺利。但是,在我点击组合框后,我的主角就不能再被键盘控制了。我需要点击我的主角让它再次聚焦。

有什么方法可以自动设置焦点?

非常感谢。

【问题讨论】:

  • 如果您希望我们帮助您,我们需要您提供minimal reproducible example
  • 而不是protagonist-&gt;setFocus(); 试试view-&gt;setFocus();
  • @scopchanov 那行得通!非常感谢!
  • 不客气!
  • @scopchanov 抱歉,已接受

标签: c++ qt


【解决方案1】:

通过单击 QComboBoxQGraphicsView 会失去焦点。您尝试通过在 QGraphicsPixmapItem 上调用 setFocus(); 将其返回。这种方法并不能如您所愿,因为它将焦点项设置在视图内,但视图本身仍然没有焦点。要在MainWindow::sceneScaleChanged 而不是protagonist-&gt;setFocus(); 中解决这个问题,请写view-&gt;setFocus();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2017-06-14
    • 2018-04-30
    相关资源
    最近更新 更多