简体   繁体   English

Qt使用自己的窗口小部件拖放?

[英]Qt Drag&Drop with own widgets?

I created a little widget on my own, including a QProgressBar and a QLabel in a QVBoxLayout. 我自己创建了一个小部件,包括QProgressBar和QVBoxLayout中的QLabel。 It has also a function which returns the text of the label (self-created). 它还具有一个返回标签文本(自行创建)的功能。 Now in my MainWindow I have two other QHBoxLayouts and I want to drag and drop my widget from one to another. 现在在MainWindow中,我还有另外两个QHBoxLayouts,我想将小部件从一个拖放到另一个。 It also works when I click on the little free space between the QLabel and the QProgressBar. 当我单击QLabel和QProgressBar之间的少量可用空间时,它也起作用。 But when I click on one of them directly, the application crashed and burned painfully. 但是,当我直接单击其中之一时,该应用程序崩溃并痛苦地刻录。
I also know where it fails. 我也知道它失败了。 My mousePressEvent looks like this: 我的mousePressEvent看起来像这样:

void DragDrop::mousePressEvent(QMouseEvent *event) {

// !!!!---- make sure ONLY MyWidgets are here, else: CRASH ----!!!!
    MyWidget *child = static_cast<MyWidget*>(childAt(event->pos()));
    if (!child)
    return;

qDebug() << child->returnLabelText();
...

}

So when I click on the ProgressBar, it will cast the ProgressBar, not my own widget. 因此,当我单击ProgressBar时,它将投射ProgressBar,而不是我自己的窗口小部件。 And because the QProgressBar doesn't have a function like returnLabelText() (but my widget does) it fails. 而且因为QProgressBar没有像returnLabelText()这样的函数(但是我的小部件有),所以它失败了。
What is a better method to get my widget? 什么是获取我的小部件的更好方法?

QWidget::childAt(int,int) returns the child widget, not the parent widget. QWidget :: childAt(int,int)返回窗口小部件,而不是父窗口小部件。 In your case, it returns the QProgressBar. 在您的情况下,它将返回QProgressBar。 You then try to cast into a MyWidget, which it is not. 然后,您尝试投射到MyWidget中,事实并非如此。 What you are looking for is for the parent of the QProgressBar (or QLabel). 您正在寻找的是QProgressBar(或QLabel)的父级。

static_cast does not verify the type of the object you are trying to cast, and will always yield a non-null pointer even if the cast is invalid. static_cast不会验证您要static_cast的对象的类型,并且即使static_cast无效,也始终会生成非空指针。 What you are looking for here is dynamic_cast , which will return NULL if the object is not of the type you are looking for. 您在这里寻找的是dynamic_cast ,如果对象不是您要寻找的类型,它将返回NULL。 Since you are looking for the parent (or an ancestor) of the widget being clicked, you could use a loop to iterate through the clicked widget's ancestry to find the instance of MyWidget you are looking for. 由于您要查找被单击的窗口小部件的父级(或祖先),因此可以使用循环来循环访问被单击的窗口小部件的祖先,以查找所需的MyWidget实例。

void DragDrop::mousePressEvent(QMouseEvent *event) {
  QWidget *widget = childAt(event->pos());
  do {
    MyWidget *myWidget = dynamic_cast<MyWidget*>(widget);
    widget = widget->parentWidget();
  } while (myWidget == NULL && widget != NULL)
  if (myWidget == NULL)
    return;

  qDebug() << myWidget->returnLabelText();
  // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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