使用 QGraphicsScene 在 QT 中跟踪计数的文本字段
Text field keeping track of count in QT using QGraphicsScene
我有一个 QT 项目(使用 C++),其中某个名为 Person
的用户定义 QGraphicsItem
的实例在场景中移动。有时这些 Persons
相互作用,因此其中一些会改变颜色。
现在我想在 window 中放置一个文本字段并显示每种颜色的数量。但是由于更改发生在对 Person::advance
方法的调用中,我想创建一个可以从其中更新的文本字段。
我可以通过将以下代码添加到 main.cpp:
来轻松显示一些文本
QGraphicsSimpleTextItem *text1 = new QGraphicsSimpleTextItem;
text1->setPos(-200, -150);
text1->setText("This is an arbitrary English sentence");
scene.addItem(text1);
但我不知道如何从场景中 Persons
的 advance
方法中访问和更改此变量 text1
的文本。什么是好的策略?
Should I create a global variable keeping track of the count, and if I do, how can I then update the text field? Or should the text not even be on my QGraphicsScene
, but rather be defined in some other more appropriate place where it is callable from everywhere in the program? Is there a generic way of doing this?
您可以使用 subclass QGraphicsObject
而不是 QGraphicsItem
,这样您就可以使用来自 Person class 的信号。然后向计算项目的插槽发出信号并更改 text1 的文本。
我要做的是将您的图形视图移动到新的 QWidget
类型 class(如 QMainWindow
)。这是为了更容易处理信号和槽,它也将允许您使用成员变量。它也比在 main.cpp
.
中做所有事情更干净
您可以将 text1
变量作为此 MainWindow
class 的成员变量。这将使访问变得容易。
您在 MainWindow
class 中的位置可能如下所示:
MainWindow::countItems()
{
int redcount = 0;
int greencount = 0;
int bluecount = 0;
// iterate through your `Person` items and check their colors and count them
text1->setText(QString("Red items: %1, Green items: %2, Blue items: %3").arg(redcount).arg(greencount).arg(bluecount));
}
您可以改进逻辑,但这只是一个基本示例。
我有一个 QT 项目(使用 C++),其中某个名为 Person
的用户定义 QGraphicsItem
的实例在场景中移动。有时这些 Persons
相互作用,因此其中一些会改变颜色。
现在我想在 window 中放置一个文本字段并显示每种颜色的数量。但是由于更改发生在对 Person::advance
方法的调用中,我想创建一个可以从其中更新的文本字段。
我可以通过将以下代码添加到 main.cpp:
来轻松显示一些文本 QGraphicsSimpleTextItem *text1 = new QGraphicsSimpleTextItem;
text1->setPos(-200, -150);
text1->setText("This is an arbitrary English sentence");
scene.addItem(text1);
但我不知道如何从场景中 Persons
的 advance
方法中访问和更改此变量 text1
的文本。什么是好的策略?
Should I create a global variable keeping track of the count, and if I do, how can I then update the text field? Or should the text not even be on my
QGraphicsScene
, but rather be defined in some other more appropriate place where it is callable from everywhere in the program? Is there a generic way of doing this?
您可以使用 subclass QGraphicsObject
而不是 QGraphicsItem
,这样您就可以使用来自 Person class 的信号。然后向计算项目的插槽发出信号并更改 text1 的文本。
我要做的是将您的图形视图移动到新的 QWidget
类型 class(如 QMainWindow
)。这是为了更容易处理信号和槽,它也将允许您使用成员变量。它也比在 main.cpp
.
您可以将 text1
变量作为此 MainWindow
class 的成员变量。这将使访问变得容易。
您在 MainWindow
class 中的位置可能如下所示:
MainWindow::countItems()
{
int redcount = 0;
int greencount = 0;
int bluecount = 0;
// iterate through your `Person` items and check their colors and count them
text1->setText(QString("Red items: %1, Green items: %2, Blue items: %3").arg(redcount).arg(greencount).arg(bluecount));
}
您可以改进逻辑,但这只是一个基本示例。