简体   繁体   中英

QT painting to widget

I'm learning QT5 for fun, and I'm learning about painting to widgets for a 2d game. I've been looking through lots of tutorials and documentation, and want to get some input on where to research from here.

From what I've learned, it seems like painting can only be done in the paintEvent function. I'm trying to figure out how make it so that I can conditionally paint something on a widget depending on keyboard input. For example, I want to make it print "alpha" if I press a, and "beta" if I press b.

Obviously I could do this by a global string variable, but what would some other ways be? I'm looking for the proper QT way to do this, any suggestions? How would you implement the following psudocode?

void paintEvent(QPaintEvent*)
{
  QPainter painter(this);

  //painter.drawText(QPoint(100,100), "example");

 }


void keyPressEvent( QKeyEvent *k )
{
    QString temp = k->text();

    if(temp == "a") 
        //paint "alpha"
    if(temp == "b")
        //paint "beta"
}

Thanks in advance!

You should use QGraphicsScene . It's more high level than paintEvent , it has many convenient abilities and should be used if you want to paint something that is not entirely trivial.

For example, in your case you need to store QGraphicsTextItem* text_item variable as a class member. In the initialization you do the following:

text_item = scene->addText("initial text");

When you decided to change text, simply use this object:

text_item->setPlainText("new_text");

Graphics view framework will repaint appropriate area for you.

This is not a complete example. You need to add a view to your widget and initialize a scene to get this work. Please refer to the Graphics View Framework page for more details.

You're pretty much there. You'd use a member variable, not a global. I'd write your keypress method like this:

class MyWidget : public QWidget {
    protected:
        void paintEvent(QPaintEvent*);
        void keyPressEvent(QKeyEvent*);
    private:
        QString mText;
};

...

void MyWidget::keyPressEvent(QKeyEvent *k) {
    if(k->key() == Qt::Key_A)
        mText = "alpha";
    else if(k->key() == Qt::Key_B)
        mText = "beta";

    update();
}

Using key() is going to be a lot safer than magic string comparisons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM