8MainWindow::MainWindow()
10 QMenu *fileMenu =
new QMenu(tr(
"&File"));
12 QAction *quitAction = fileMenu->addAction(tr(
"E&xit"));
13 quitAction->setShortcut(tr(
"Ctrl+Q"));
15 QMenu *itemsMenu =
new QMenu(tr(
"&Items"));
17 insertAction = itemsMenu->addAction(tr(
"&Insert Item"));
18 removeAction = itemsMenu->addAction(tr(
"&Remove Item"));
19 QAction *ascendingAction = itemsMenu->addAction(tr(
"Sort in &Ascending Order"));
20 QAction *descendingAction = itemsMenu->addAction(tr(
"Sort in &Descending Order"));
22 menuBar()->addMenu(fileMenu);
23 menuBar()->addMenu(itemsMenu);
26
27
28
29
30 listWidget =
new QListWidget(
this);
31 listWidget->setSelectionMode(QAbstractItemView::SingleSelection);
33 connect(quitAction, &QAction::triggered,
this, &QWidget::close);
34 connect(ascendingAction, &QAction::triggered,
this, &MainWindow::sortAscending);
35 connect(descendingAction, &QAction::triggered,
this, &MainWindow::sortDescending);
36 connect(insertAction, &QAction::triggered,
this, &MainWindow::insertItem);
37 connect(removeAction, &QAction::triggered,
this, &MainWindow::removeItem);
38 connect(listWidget, &QListWidget::currentItemChanged,
39 this, &MainWindow::updateMenus);
42 updateMenus(listWidget->currentItem());
44 setCentralWidget(listWidget);
45 setWindowTitle(tr(
"List Widget"));
48void MainWindow::setupListItems()
51 new QListWidgetItem(tr(
"Oak"), listWidget);
52 new QListWidgetItem(tr(
"Fir"), listWidget);
53 new QListWidgetItem(tr(
"Pine"), listWidget);
55 new QListWidgetItem(tr(
"Birch"), listWidget);
57 new QListWidgetItem(tr(
"Hazel"), listWidget);
59 new QListWidgetItem(tr(
"Redwood"), listWidget);
61 new QListWidgetItem(tr(
"Sycamore"), listWidget);
62 new QListWidgetItem(tr(
"Chestnut"), listWidget);
63 new QListWidgetItem(tr(
"Mahogany"), listWidget);
67void MainWindow::sortAscending()
70 listWidget->sortItems(Qt::AscendingOrder);
74void MainWindow::sortDescending()
77 listWidget->sortItems(Qt::DescendingOrder);
81void MainWindow::insertItem()
83 if (!listWidget->currentItem())
86 QString itemText = QInputDialog::getText(
this, tr(
"Insert Item"),
87 tr(
"Input text for the new item:"));
89 if (itemText.isNull())
93 QListWidgetItem *newItem =
new QListWidgetItem;
94 newItem->setText(itemText);
96 int row = listWidget->row(listWidget->currentItem());
98 listWidget->insertItem(row, newItem);
101 QString toolTipText = tr(
"Tooltip:") + itemText;
102 QString statusTipText = tr(
"Status tip:") + itemText;
103 QString whatsThisText = tr(
"What's This?:") + itemText;
105 newItem->setToolTip(toolTipText);
106 newItem->setStatusTip(toolTipText);
107 newItem->setWhatsThis(whatsThisText);
111void MainWindow::removeItem()
113 listWidget->takeItem(listWidget->row(listWidget->currentItem()));
116void MainWindow::updateMenus(QListWidgetItem *current)
118 insertAction->setEnabled(current != 0);
119 removeAction->setEnabled(current != 0);