gpt4 book ai didi

c++ - 在 QT Creator 中动态更改 x 和 y 坐标

转载 作者:行者123 更新时间:2023-11-28 06:00:02 25 4
gpt4 key购买 nike

我希望在 QT 中动态传递椭圆的 x 和 y 坐标。我尝试了以下操作,看起来 setPos(x, y) 函数实际上并没有真正转换椭圆,直到 on_pushButton_2_clicked() 返回。

我有两个按钮,pushButton1pushButton2,第一个是创建椭圆(并确保另一个按钮在调用后不会被创建),另一个是应该更改传递的坐标。

void MainWindow::on_pushButton_clicked()
{
int hasRun = 0;
while(!hasRun)
{
QBrush green(Qt::green);
QBrush blue(Qt::blue);
QPen blackPen(Qt::black);
blackPen.setWidth(2);
ellipse = scene -> addEllipse(10, 10, 25, 25, blackPen, green);
hasRun = 1;
flag = 1;
}
}

void MainWindow::change(int x, int y)
{
ellipse->setPos(x, y);
cout << "width: " << ui->graphicsView->width() << endl;
cout << "height: " << ui->graphicsView->height() << endl;
}

void MainWindow::on_pushButton_2_clicked()
{
int i = 0;
while(i < 25)
{
change(i, i);
Sleep(200);
i++;
}
}

我们将不胜感激。

最佳答案

问题是您通过休眠操作阻塞了 UI 线程,这意味着 UI 永远不会被重绘,因此在单击的函数返回之前您看不到 UI 更新。

解决此问题的最简单方法是使用 QTimer 1 ,它允许您安排将来的事件。当计时器到期(超时)时,它将调用您的事件处理程序。但是,它不会在等待时阻塞 UI 线程。您可以使用类似这样的方法来实现所需的动画效果:

auto timer = new QTimer(this);

// Define the timeout slow for the timer.
connect(timer, &QTimer::timeout, [timer, ellipse]() {
auto x = ellipse->x();
auto y = ellipse->y();

// If we have reached our target position, stop the timer.
if (x == 25) {
timer->stop();
return;
}

// Otherwise update the position.
ellipse->setPos(x + 1, y + 1);
});

// Start the timer. The timeout slot we defined above will be called every ~200ms.
timer->start(200);

一个更好的方法是通过 QPropertyAnimation 使用 Qt 动画支持 2 ,它允许您设置属性的开始和结束时间和值,然后将自动在它们之间进行插值。有关使用示例,请参阅文档。但是,对于您的情况,因为您不是 QObject 子类的动画,所以您不能这样做。

一般来说,如果您需要执行一项耗时的任务,您应该在后台线程上执行,以避免阻塞 UI 线程,否则您的应用会卡住。

关于c++ - 在 QT Creator 中动态更改 x 和 y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com