如何在QGridLayout中获取窗口小部件的行/列位置?

use*_*292 2 qt qpushbutton

我创建了一个自己的GridPushButton类来存储gridlayout中的按钮位置.父母是QPushButton.我在窗口询问它的x和y坐标时有问题(比如x:654,y:768).我以为它将继承自基类,但事实并非如此.现在我有两个选择:

  1. 使用原始QPushButton类并以某种方式获得它在gridlayout中的位置(如x:0,y:1,如果它在第一行和第二列)或

  2. 使用我的GridPushButton并以某种方式获取窗口中的x和y坐标.

    class GridPushButton : public QPushButton
    {
    Q_OBJECT
    public:
      GridPushButton(int coordX, int coordY, QWidget *parent = 0);
      int coordinateX() { return _coordX; }
      int coordinateY() { return _coordY; }
    
    protected:
      int _coordX;
      int _coordY;
    };
    
    Run Code Online (Sandbox Code Playgroud)

这是我的班级.我试图创建一个新的私有变量并给它QPushButton::x(),但不起作用.有没有想过从父母那里获得x和y坐标?或者想知道QPushButtons在GridLayout中获得该职位的想法?

Rei*_*ica 8

您正在混合两种坐标概念.父窗口小部件中有位置.这是通过使用 QWidget::x(),QWidget::y()QWidget::pos()方法.你不需要在这里实现任何东西:它已经有效了.

然后是网格布局中行和列的概念.这可以在不需要任何子类化的情况下获得.网格布局知道其小部件的位置,您可以简单地询问它是否有任何小部件的行/列位置.

截图

#include <QtWidgets>

struct Pos { int row, col ; };

Pos gridPosition(QWidget * widget) {
  Pos result{};
  if (! widget->parentWidget()) return pos;
  auto layout = qobject_cast<QGridLayout*>(widget->parentWidget()->layout());
  if (! layout) return pos;
  int index = layout->indexOf(widget);
  Q_ASSERT(index >= 0);
  int _;
  layout->getItemPosition(index, &pos.row, &pos.col, &_, &_);
  return pos;
}

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   QWidget w;
   QGridLayout l(&w);
   QLabel gridPos;
   l.addWidget(&gridPos, 0, 0, 1, 4);
   for (int i = 1; i < 4; ++ i)
      for (int j = 0; j < 3; ++ j) {
         auto b = new QPushButton(QString("%1,%2").arg(i).arg(j));
         l.addWidget(b, i, j);
         QObject::connect(b, &QPushButton::clicked, [&gridPos, b]{
            auto p = gridPosition(b);
            gridPos.setText(QString("Grid Pos: %1,%2")
                            .arg(p.row).arg(p.col));
         });
      }
   w.show();
   return a.exec();
}
Run Code Online (Sandbox Code Playgroud)