简体   繁体   English

在 QWidget 中包装 QLabel 以使其像带有图像的枚举一样

[英]Wrapping up a QLabel in a QWidget to make it act like an enum with an image

I have a label on my MainWindow and I am setting the RichText to be a static image that comes from my resource file.我的 MainWindow 上有一个 label,我将 RichText 设置为来自我的资源文件的 static 图像。 This works great, but I want to abstract away the fact that this is a label and expose a single method called SetImage(std::string path);这很好用,但我想抽象出这是一个 label 并公开一个名为SetImage(std::string path);的方法。 so I can make this work more like an enumeration of images.所以我可以让这项工作更像是图像的枚举。

Thinking about it, if I wanted to do something like this irrespective of a framework or image, my feeling would be to contain a label inside a class to abstract away the fact that I'm using a label in this way.考虑一下,如果我想做这样的事情而不考虑框架或图像,我的感觉是在 class 中包含一个 label 以抽象出我以这种方式使用 ZD304BA20E96D870E341588EEABAC8 的事实。

So, I would have something like this in QT:所以,我会在 QT 中有这样的东西:

class QMyWidget : public QWidget {
public:
  explicit QMyWidget(QWidget* parent = nullptr);
  virtual ~QMyWidget();
  SetImage(const std::string& path);
private:
   QLabel* m_label;
};

and then calling SetImage would do something like然后调用 SetImage 会做类似的事情

QMyWidget::SetImage(const std::string& path){
   //setup label for rich text;
   std::string richText("//format rich text string here to load the image resource");
   m_label->SetText(richText);
};

Is this the right way to go about this, or is there a better, more "QT" way to solve this problem?这是 go 关于这个问题的正确方法,还是有更好、更“QT”的方法来解决这个问题? I'm trying to avoid doing a bunch of heavy lifting in the designer or something like that.我试图避免在设计师中做大量繁重的工作或类似的事情。

This is a working solution to hide the implementation details.这是隐藏实现细节的有效解决方案。

You may also consider using QImage or at least one of the image classes instead of QLabel though.您也可以考虑使用 QImage 或至少一个图像类而不是 QLabel。

Also, the method is spelled as setText , not SetText on it.此外,该方法拼写为setText ,而不是SetText

Also, a minot nitpick, but in a Qt project, you may want to use QString instead of std::string in case the name is not ascii, but utf.此外,还有一点挑剔,但在 Qt 项目中,如果名称不是 ascii 而是 utf,您可能需要使用 QString 而不是 std::string。

Another nitpick, mark your destructor with override and make it = default .另一个挑剔,用override标记你的析构函数并使其= default

Also, use a more meaningful name than QMyWidget .此外,使用比QMyWidget更有意义的名称。

As a matter of preference of mine, I would also not leave the Q_OBJECT out in the class.作为我的偏好,我也不会将Q_OBJECT留在 class 中。 It may not be required now, but it can always help with debugging, when you add signals and slots, etc, and then it can cause headaches why things do not work.现在可能不需要它,但它总是可以帮助调试,当你添加信号和插槽等时,然后它会让人头疼,为什么事情不工作。

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

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