我是qt的新手,正在使用qt c ++进行红黑树可视化。我已经使用Qpaint创建了节点结构,并用基本的数据结构树代码准备好了即时消息,唯一的问题是更新了paint事件coz,我也想在需要时调用paint事件。
在绘画时,我的初始节点也消失了。请仔细阅读代码并提供帮助。
代码是:
//dispaymenu.cpp
#include "displaymenu.h"
#include "ui_displaymenu.h"
#include "datastruct.cpp"
#include<QtCore>
#include<QtGui>
DisplayMenu::DisplayMenu(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::DisplayMenu)
{
ui->setupUi(this);
}
DisplayMenu::~DisplayMenu()
{
delete ui;
}
void DisplayMenu::paintEvent(QPaintEvent *)
{
createNode(text,col);
}
void DisplayMenu::createNode(QString text,char col)
{
QRectF rect(x,y,80,80); //create rectangle object which is not seen
QPainter p(this);
if(col=='b')
p.setBrush(Qt::black);
else if(col=='r')
p.setBrush(Qt::red);
p.drawEllipse(rect); //circle fits into the rect passed
p.setPen(Qt::white);
p.setFont(QFont("Arial", 15)); //to set font and size of text
p.drawText(rect, Qt::AlignCenter,text);
}
void DisplayMenu::setText()
{
bool ok;
text = QInputDialog::getText(this, tr("getText()"),
tr("getdata:"), QLineEdit::Normal,
QDir::home().dirName(), &ok);
if (ok && !text.isEmpty())
{
int ele=text.toInt();
RBTree t1(a);
col=t1.insert(ele);
a=1;
createNode(text,col);
}
}
void DisplayMenu::on_textButton_clicked()
{
setText();
}
this was our mainwindow file.
//main.cpp
#include "displaymenu.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
displaymenu w;
w.show();
return a.exec();
}
//datastruct.cpp
#include <bits/stdc++.h>
#include<datastruct.h>
#include<displaymenu.h>
#include"displaymenu.cpp"
using namespace std;
enum Color {RED, BLACK};
struct Node
{
int data;
char color;
Node *left, *right, *parent;
// Constructor
Node(int data)
{
this->data = data;
this->color='r';
left = right = parent =nullptr;
}
};
// Class to represent Red-Black Tree
class RBTree
{
public:
Node *root;
void rotateLeft(Node *&, Node *&);
void rotateRight(Node *&, Node *&);
void fixViolation(Node *&, Node *&);
// Constructor
RBTree(int a)
{
if(a==0)
root = nullptr;
}
char insert(int ele);
//void inorder();
//void levelOrder();
};
Node* BSTInsert(Node* root, Node *pt)
{
//DisplayMenu d(&p);
/* If the tree is empty, return a new node */
if (root == nullptr)
{
pt->color='b';
return pt;
}
/* Otherwise, recur down the tree */
if (pt->data < root->data)
{
root->left = BSTInsert(root->left, pt);
root->left->parent = root;
}
else if (pt->data > root->data)
{
root->right = BSTInsert(root->right, pt);
root->right->parent = root;
}
/* return the (unchanged) node pointer */
return root;
}
char RBTree::insert(int data)
{
Node *pt = new Node(data);
// Do a normal BST insert
root=BSTInsert(root, pt);
return pt->color;
// fix Red Black Tree violations
//fixViolation(root, pt);
}
答案 0 :(得分:1)
调用QWidget::update()
在您的小部件上创建一个新的绘画事件。该事件将由事件循环尽快处理。
您还可以强制调用QWidget::repaint
进行重画,但是您将停止事件循环(因此,仅在需要即时重画时)。