I'm relatively new to QT. In my code, I create a QTableWidget, iterate through the rows and set the cells to QLineEdits and QCheckBoxes. I want to make it so that changing the text within any of the QLineEdits or checking/unchecking the QCheckBoxes causes my table to fire a signal passing either the item in question, or the row/column that it's within.
I build the table here:
for(int row=0; row < conditionTable->rowCount(); row++)
{
QLineEdit *condition = new QLineEdit;
conditionTable->setCellWidget(row, 0, condition);
QLineEdit *minBoundField = new QLineEdit;
conditionTable->setCellWidget(row, 1, minBoundField);
QLineEdit *maxBoundField = new QLineEdit;
conditionTable->setCellWidget(row, 2, maxBoundField);
QCheckBox *checkbox = new QCheckBox;
conditionTable->setCellWidget(row, 3, checkbox);
if(row > 0)
{
condition->setReadOnly(true);
minBoundField->setReadOnly(true);
maxBoundField->setReadOnly(true);
checkbox->setCheckable(false);
}
}
I then try to make it so that changes to the table can be handled by one of the slot methods:
connect(conditionTable, SIGNAL(itemChanged(QTableWidgetItem*)),
this, SLOT(handleConditionTableChange(QTableWidgetItem*)));
However, this doesn't seem to work, and I'm not sure where to go from here. Any help would be appreciated.
You shouldn't be using QLineEdit and QCheckBox here.
To add a check box to your QTableWidget do the following:
QTableWidgetItem* item = new QTableWidgetItem("check box");
item->setFlags(Qt::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked);
tableWidget->setItem(row, column, item);
To add an line edit:
QTableWidgetItem* item = new QTableWidgetItem("line edit");
tableWidget->setItem(row, column, item);
With this setup, the signal will be emitted when an item is changed.
Edit:
For your example, try something like:
for(int row=0; row < conditionTable->rowCount(); row++)
{
QTableWidgetItem* condition = new QTableWidgetItem("");
conditionTable->setItem(row, 0, condition);
QTableWidgetItem *minBoundField = new QTableWidgetItem("");
conditionTable->setItem(row, 1, minBoundField);
QTableWidgetItem *maxBoundField = new QTableWidgetItem("");
conditionTable->setItem(row, 2, maxBoundField);
QTableWidgetItem *checkbox = new QTableWidgetItem("");
checkbox->setFlags(Qt::ItemIsUserCheckable);
checkbox->setCheckState(Qt::Unchecked);
conditionTable->setItem(row, 3, checkbox);
if(row > 0)
{
condition->setFlags(Qt::NoItemFlags);
minBoundField->setFlags(Qt::NoItemFlags);
maxBoundField->setFlags(Qt::NoItemFlags);
checkbox->setFlags(Qt::NoItemFlags);
}
}
If you still want to use QLineEdit and QCheckBox for some reason, you will need to connect each line edit and each check box to a slot.
Related
I am working on Qt applicaction. There I have QMainWindow. Inside it I have added QTableView. When I run the application I see that I need to scroll to display the whole table and also blank space shows up below it.
I would like main window to resize horizontally in order to use space needed by the table. Also I would like it to resize vertically to not having space unused. How could I achieve that?
This is my code so far:
void MainWindow::initUi() {
setWindowTitle(tr("Main Window"));
QWidget* centralWidget = new QWidget(this);
QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
QFormLayout *upperLayout = new QFormLayout;
// Default layout appearance of QMacStyle
upperLayout->setRowWrapPolicy(QFormLayout::DontWrapRows);
upperLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
upperLayout->setFormAlignment(Qt::AlignHCenter | Qt::AlignTop);
upperLayout->setLabelAlignment(Qt::AlignLeft);
QVBoxLayout *resultsLayout = new QVBoxLayout;
QTableView* table = new QTableView(centralWidget);
table->verticalHeader()->hide();
QStandardItemModel* model= new QStandardItemModel(4, 4);
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
model->setItem(row, column, item);
}
}
table->setModel(model);
QLabel* upperLabel = new QLabel(tr("Label:"), centralWidget);
upperLabel->setAlignment(Qt::AlignLeft);
resultLabel = new QLabel(tr("Result goes here"), centralWidget);
mainLayout->addLayout(resultsLayout);
resultsLayout->addLayout(upperLayout);
resultsLayout->addWidget(table);
upperLayout->addRow(upperLabel, resultLabel);
centralWidget->setLayout(mainLayout);
setCentralWidget(centralWidget);
this->adjustSize();
}
Set the sizeAdjustPolicy of the table to AdjustToContents view, then set the size policy to Fixed in both horizontal and vertical directions.
AdjustToContents might incur a slight performance penalty for dynamic contents in the view, since every data change may change the layout.
The Qt Designer is a really nifty tool to figure layout issues out quickly; the {table,list,tree} widgets behave exactly the same as the views do (because they're the same) and the widgets can be quickly filled with dummy data in Qt Designer.
I want to do a list that changes it's fields numbers when the user changes a the value of a spinbox.
Something like this:
First 5 fields by default
Then just 1 field for example
And if the user wants to change it again, he can put 5 fields again.
I made a GridLayout and a couple of QList, one for the Labels and the other one for LineEdits. I did this:
I create a basic case (with just 1 field) and i later add more on excecution time adding Widgets to the GridLayout by:
gridLayout->addWidget(labels.at(x), 0, 1)
where labels is the QList. it works fine to add widgets but i can't remove and add again.
i tried using
gridLayout->removeWidget(lables.at(x), 0, 1)
labels.at(x)->hide()
label.at(x)->setVisible(false)
all works but i can't show it again with none of this:
gridLayout->addWidget(labels.at(x), 0, 1)
labels.at(x)->show()
label.at(x)->setVisible(true)
Layouts are handlers of the geometry of the widgets. If you use the removeWidget() function, you will only remove that element from the layout but it will still be visible. If you want it not to be visible you have to delete it with delete.
In the following example I show you how to add and remove the widgets using the valueChanged signal of the QSpinBox.
void Dialog::on_spinBox_valueChanged(int arg1)
{
int nElements = labels.count();
//add
if(arg1 > nElements){
for(int i=nElements; i < arg1; i++){
QLabel *label = new QLabel(QString::number(i), this);
QLineEdit *line = new QLineEdit(QString::number(i), this);
labels.append(label);
lines.append(line);
ui->gridLayout->addWidget(label, i, 0, 1, 1);
ui->gridLayout->addWidget(line, i, 1, 1, 1);
}
}
//remove
else if(arg1 < nElements){
for(int i=arg1; i < nElements; i++){
QLabel *label = labels.at(i);
QLineEdit *line = lines.at(i);
ui->gridLayout->removeWidget(label);
ui->gridLayout->removeWidget(line);
labels.removeAt(i);
lines.removeAt(i);
delete label;
delete line;
}
}
}
Add:
Remove:
I need to add a widget (QTableWidget) into QFileDialog's layout. I know that it is QGridLayout with sizes (3,4). The table must be in 3-rd row and span all columns.
QTableWidget* tableWidget = new QTableWidget(this);
QGridLayout *layout = static_cast<QGridLayout*>(QFileDialog::layout());
layout->addWidget(tableWidget, 2, 0, 1, 4);
With this code the original 3-rd row which contains lineEdit and save/open pushButton disappears. How can I add widgets between already existing widgets of QGridLayout so that original widgets remain in the layout.
I strongly recommend you not to rely on QFileDialog's implementation. The layout can be different on different platforms or different versions of Qt. It may be more correct to place your table under the dialog or to the right of it. This can be done easily without altering the layout of the QFileDialog itself. Just create a QVBoxLayout and put QFileDialog and QTableWidget inside it.
However, the question has been asked, and the solution exists. QGridLayout has no functionality such as QBoxLayout::insertItem. So we need to implement this behavior manually. The plan is:
Obtain the list of layout items placed in 3rd and 4th rows.
Calculate new positions of items.
Take elements out of item and add them back at new positions.
Working code:
QFileDialog* f = new QFileDialog();
f->setOption(QFileDialog::DontUseNativeDialog, true); //we need qt layout
QGridLayout *layout = static_cast<QGridLayout*>(f->layout());
QList< QPair<QLayoutItem*, QList<int> > > moved_items;
f->show();
for(int i = 0; i < layout->count(); i++) {
int row, column, rowSpan, columnSpan;
layout->getItemPosition(i, &row, &column, &rowSpan, &columnSpan);
if (row >= 2) {
QList<int> list;
list << (row + 1) << column << rowSpan << columnSpan;
moved_items << qMakePair(layout->takeAt(i), list);
i--; // takeAt has shifted the rest items
}
}
for(int i = 0; i < moved_items.count(); i++) {
layout->addItem(moved_items[i].first,
moved_items[i].second[0],
moved_items[i].second[1],
moved_items[i].second[2],
moved_items[i].second[3]);
}
QTableWidget* tableWidget = new QTableWidget();
layout->addWidget(tableWidget, 2, 0, 1, 4);
All, I am maintaining a QGridLayout of QLabels which show the coefficients of a polynomial. I represent my polynomial using QList<double>.
Each time I update my coefficients, I update my labels. When changing the size of the list, my method does not works well. QGridLayout::rowCount() doesn't update correctly. I am wondering if there's a way to remove rows from a QGridLayout.
Code follows, updating the QGridLayout size with more (or less) QLabels
int count = coefficients->count(); //coefficients is a QList<double> *
if(count != (m_informational->rowCount() - 1)) //m_information is a QGridLayout
{
SetFitMethod(0);
for(int i = 0; i < count; ++i)
{
QLabel * new_coeff = new QLabel(this);
new_coeff->setAlignment(Qt::AlignRight);
m_informational->addWidget(new_coeff, i+1, 0);
QLabel * param = new QLabel(this);
param->setAlignment(Qt::AlignLeft);
param->setText(QString("<b><i>x</i><sup>%2</sup></b>").arg(count-i-1));
m_informational->addWidget(param, i+1, 1);
QSpacerItem * space = new QSpacerItem(0,0,QSizePolicy::Expanding);
m_informational->addItem(space, i+1, 1);
}
m_informational->setColumnStretch(0, 3);
m_informational->setColumnStretch(1, 1);
m_informational->setColumnStretch(2, 1);
}
The SetFitMethod (it's an initial mockup)
void SetFitMethod(int method)
{
ClearInformational();
switch(method)
{
case 0: //Polynomial fit
QLabel * title = new QLabel(this);
title->setText("<b> <u> Coefficients </u> </b>");
title->setAlignment(Qt::AlignHCenter);
m_informational->addWidget(title,0,0,1,3, Qt::AlignHCenter);
}
}
The Clearing Method:
void ClearInformational()
{
while(m_informational->count())
{
QLayoutItem * cur_item = m_informational->takeAt(0);
if(cur_item->widget())
delete cur_item->widget();
delete cur_item;
}
}
The issue is that QGridLayout::rowCount() doesn't actually return the number of rows that you can see, it actually returns the number of rows that QGridLayout has internally allocated for rows of data (yes, this isn't very obvious and isn't documented).
To get around this you can either delete the QGridLayout and recreate it, or if you're convinced that your column count won't change, you can do something like this:
int rowCount = m_informational->count()/m_informational->columnCount();
I solved this by creating a QVBoxLayout (for rows) and within this I was adding QHBoxLayout (for columns). In the QHBoxLayout I was then inserting my widgets (in one row). This way I was able to nicely remove rows - overall row count was working as it should be. Additionally to this I got also an insert method, thanks to which I was able to insert new rows into specific locations (everything was correctly reordered/renumbered).
Example (only from head):
QVBoxLayout *vBox= new QVBoxLayout(this);
//creating row 1
QHBoxLayout *row1 = new QHBoxLayout();
QPushButton *btn1x1 = new QPushButton("1x1");
QPushButton *btn1x2 = new QPushButton("1x2");
row1->addWidget(btn1x1);
row1->addWidget(btn1x2);
//adding to vBox - here you can use also insertLayout() for insert to specific location
vBox->addlayout(row1);
//creating row 2
QHBoxLayout *row2 = new QHBoxLayout();
QPushButton *btn2x1 = new QPushButton("2x1");
QPushButton *btn2x2 = new QPushButton("2x2");
row2->addWidget(btn2x1);
row2->addWidget(btn2x2);
//adding to vBox - here you can use also insertLayout() for insert to specific location
vBox->addlayout(row2);
Well, my solution was to also delete the QGridLayout in ClearInformational
Is it possible to put multiple lines of text in one row of QTableWidget?
I can think about 2 ways to force tablewidget to render multi-line text:
Setup QStyledItemDelegate item delegate and render text yourself in the delegates paint method. Here you can find an example of you could do the same thing to a listview.
Another solution would be to set QTextEdit as a cell widget to the table widget via setCellWidget method.
Below is an example for #2:
QTableWidget* tableWidget = new QTableWidget(3, 2, this);
tableWidget->setGeometry(20, 20, 300, 300);
for (int row = 0; row<3; row++)
{
for (int column=0; column<2; column++)
{
QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1 long long long long long long text").arg((row+1)*(column+1)));
tableWidget->setItem(row, column, newItem);
}
QTextEdit *edit = new QTextEdit();
edit->setText(tableWidget->item(row, 0)->text());
tableWidget->setCellWidget(row, 0, edit);
}
hope this helps, regards
You can also simply use \n to start new line in a cell :-)
For example:
ui->tableWidget->insertRow(i);
QTableWidgetItem *newItem = new QTableWidgetItem("Line 1 \n Line 2");
ui->tableWidget->setItem(0,0,newItem);
just make vertical headers to fit the contents then use a text as long as you want.
QTableWidget::verticalHeader()->resizeSections(QHeaderView::ResizeToContents);