3

我有自定义窗口类

#define NAME_WIDTH 150
#define NAME_HEIGHT 20

ObjectWindow::ObjectWindow(QWidget * parent)
{

}

void ObjectWindow::SetKey(KeyObject * keyObj)
{
    QGridLayout * layout = new QGridLayout(this);

    nameField = new QTextEdit(this);
    nameField->setText(keyObj->name);
    nameField->setGeometry(nameField->geometry().x(), nameField->geometry().y(),
                         NAME_WIDTH, NAME_HEIGHT);
    layout->addWidget(nameField);

    QHBoxLayout * picsLayout = new QHBoxLayout(this);
    for(std::vector<ImageInstance*>::iterator imgObj = keyObj->images.begin(); imgObj != keyObj->images.end(); imgObj++)
    {
        QComboBox * folderList = new QComboBox;
        picsLayout->addWidget(folderList);

        QImage image((*imgObj)->imgPath);
        QLabel * picLabel = new QLabel;
        picLabel->setPixmap(QPixmap::fromImage(image).scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        picsLayout->addWidget(picLabel);
    }
    layout->addLayout(picsLayout, 2, 0);


    QPushButton * saveBtn = new QPushButton(this);
    saveBtn->setText("Save");
    connect(saveBtn, SIGNAL(released()),this, SLOT(Save()));
    layout->addWidget(saveBtn);

    setLayout(layout);
}

我需要的是

  • 用于设置名称的小文本字段,我不明白为什么 SetGeometry 不起作用

  • 每个图像上方的下拉列表。我可以为每组图像和列表创建 QHVertical 布局,但也许有更简单的方法来做到这一点?

在此处输入图像描述

4

1 回答 1

2

如果您只想让用户设置名称,QLineEdit可能就足够了。

那么使用 QGridLayout 的主要优点是您不需要创建其他布局。它就像一个放置小部件的网格,有点像 Excel(和其他电子表格程序)。

哦,我看到你没有在构造函数中构造小部件(这似乎是空的),这是人们通常做的,因为构造 UI 可能很昂贵,你只想在相关时更新它,而不是重建整个 UI更新字段。但是如果没有更多代码,我无法判断何时调用此函数。

你可以尝试这样的事情:

QGridLayout * layout = new QGridLayout(this);

nameField = new QLineEdit(this);
nameField->setText(keyObj->name);
layout->addWidget(nameField, 0, 0, -1, 1); // expand to the right edge

int currentColumn = 0;
for(std::vector<ImageInstance*>::iterator imgObj = keyObj->images.begin(); imgObj != keyObj->images.end(); imgObj++)
{
    QComboBox * folderList = new QComboBox;
    layout->addWidget(folderList, 1, currentColumn);

    QPixmap pixmap((*imgObj)->imgPath);
    pixmap = pixmap.scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QLabel * picLabel = new QLabel(this);
    picLabel->setPixmap(pixmap);
    layout->addWidget(picLabel, 2, currentColumn);
    ++currentColumn;
}


QPushButton * saveBtn = new QPushButton("Save", this);
connect(saveBtn, SIGNAL(released()),this, SLOT(Save()));
layout->addWidget(saveBtn, 3, 0, -1, 1);

setLayout(layout);

但是像这样水平添加这些小部件似乎不是一个好主意。如果这个向量中有 100 个项目会发生什么?您应该调查使用 QScrollArea 之类的东西或修改 UI 以便为您的客户提供查看和编辑它们的最佳方式(但如果没有更多上下文,似乎很难提供更多建议)。

于 2014-04-07T14:36:58.593 回答