这是我的简单代码:
我创建了一个新的scene
、view
和QPixmapItem
QGraphicsScene *scena = new QGraphicsScene();
QGraphicsPixmapItem *object1= new QGraphicsPixmapItem();
object1->setPixmap(QPixmap(":/prova/prova.png"));
QGraphicsView *view = new QGraphicsView();
view->setScene(scena);
scena->addItem(object1);
view->show();
接下来我创建了一个带有两个QState
的新QStateMachine
QStateMachine *machine = new QStateMachine();
QState *s1 = new QState();
QState *s2 = new QState();
machine -> addState(s1);
machine -> addState(s2);
//mouse click in a void mousePressEvent
s1 -> addTransition(this,SIGNAL(mouseclick()),s2);
machine -> start();
我想在
s1
中显示view
,并将object1
设置为可见。用鼠标点击场景,我为
s2
添加了一个过渡。在
s2
中,我只想隐藏object1
。
我该怎么做?有人可以帮我做一个小教程吗?
我使用的是Qt 5.6.0和MinGW 4.9.2 32位。
每个QState
都有entered
和exited
信号,您可以将函子连接到它们。这是现代Qt5代码中常见的习惯用法。函数可以使用lambda表达式简洁地给出,在lambda表达式中,您可以调用非对象上的任意操作,例如QPixmapItem
。如果QPixmapItem
派生自QGraphicsObject
,则可以使用QState::assignProperty
来分配所需的可见性状态,而不是调用show()
和hide()
。
下面是一个完整的例子。
// https://github.com/KubaO/stackoverflown/tree/master/questions/scenestate-37684315
#include <QtWidgets>
void addTransition(QState * src, QObject * eventSource, QEvent::Type type, QAbstractState * dst)
{
auto transition = new QEventTransition(eventSource, type);
transition->setTargetState(dst);
src->addTransition(transition);
}
struct Window : public QWidget {
QHBoxLayout m_layout{this};
QGraphicsScene m_scene;
QGraphicsPixmapItem m_item;
QGraphicsView m_view{&m_scene};
QStateMachine m_mach;
QState s1{&m_mach};
QState s2{&m_mach};
Window() {
m_layout.addWidget(&m_view);
QPixmap pix{128, 128};
QPainter p{&pix};
p.setBrush(Qt::white);
p.drawRect(pix.rect().adjusted(0,0,-1,-1));
p.drawText(pix.rect(), "Hello");
m_item.setPixmap(pix);
m_scene.addItem(&m_item);
// I want to show the view in s1...
s1.assignProperty(&m_view, "visible", true);
// and set object1 visible.
s1.connect(&s1, &QState::entered, [&]{ m_item.show(); });
// With a mouse click on the scene I've added a transition to s2.
addTransition(&s1, &m_view, QEvent::MouseButtonPress, &s2);
// In s2 I want to hide only object1.
s2.connect(&s2, &QState::entered, [&]{ m_item.hide(); });
m_mach.setInitialState(&s1);
m_mach.start();
}
};
int main(int argc, char ** argv) {
QApplication app{argc, argv};
Window w;
w.show();
return app.exec();
}